diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d02e19..ee3069c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ All notable changes to TaskSeam will be documented here. +## 0.2.1 - 2026-11-21 + +- Fix setup for editor-only users. `taskseam setup` now finds the Claude Code and Codex + CLIs bundled inside the VS Code, VS Code Insiders, Cursor, and Windsurf extensions. + Previously it skipped any agent missing from `PATH`, so extension-only installs were + never connected. +- Add `taskseam demo`, a one-minute walkthrough in a temporary project that needs no + agents, accounts, or settings changes. +- Add `taskseam doctor`. It checks each agent's MCP registration and session-start hook + (including hooks pointing at a removed Python), locates the project or nearby projects + when an editor is opened in the wrong folder, summarizes project state, and warns when + `.taskseam/` is not ignored by Git. Every problem includes the command that fixes it. +- `taskseam setup` and `taskseam init` print plain-language next steps on standard error. + Their JSON output is unchanged. +- CI tests Python 3.9 on ubuntu-24.04 and uses Node 24 actions. + ## 0.2.0 - 2026-11-21 Upgrade with `pipx upgrade taskseam` (or `python3 -m pip install -U taskseam`), then rerun diff --git a/README.md b/README.md index 761bbd5..c9e7d1b 100644 --- a/README.md +++ b/README.md @@ -33,10 +33,11 @@ TaskSeam stores the current task state under the project's `.taskseam/` director ## Quick start -Install TaskSeam as an isolated command-line application: +Install TaskSeam as an isolated command-line application, then watch it work in a throwaway project: ```bash pipx install taskseam +taskseam demo # one minute, no agents or settings touched ``` Standard pip installation also works: @@ -45,7 +46,7 @@ Standard pip installation also works: python3 -m pip install taskseam ``` -Connect the supported agents installed on your computer: +Connect the supported agents installed on your computer. Their CLIs or VS Code/Cursor extensions are detected automatically: ```bash taskseam setup @@ -71,6 +72,7 @@ There are no routine TaskSeam commands after initialization. In Claude Code and You rarely need these, because agents record state through their approval screen. They are useful when you want to check or correct that state yourself: ```bash +taskseam doctor # is everything connected? prints the fix if not taskseam show # what every agent will see, in plain text taskseam drop 3f9a --reason "Offline mode cut" # retire an item that no longer applies taskseam export --agents-md # mirror state into AGENTS.md for non-MCP agents diff --git a/docs/DEMO.md b/docs/DEMO.md index a32084b..41c3e63 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -1,5 +1,16 @@ # End-to-end TaskSeam demo +## One minute, no setup + +```bash +pipx install taskseam +taskseam demo +``` + +`taskseam demo` runs in a temporary directory and touches no agent settings. It shows the whole loop. A decision is made in one agent and replaced in another. A new chat then starts with only current state, a returning agent receives only what changed, and every item keeps its evidence. Record it with any screen recorder, or `asciinema rec -c "taskseam demo"`. + +## With real agents + This demonstration proves that one agent can save accepted task state and another can receive only what changed. After setup, the user works through normal conversation rather than maintaining state with CLI commands. ## Prepare a clean project @@ -42,12 +53,22 @@ Approve the proposed TaskSeam write. ## Return to the first agent -Start a new session with the first agent and ask: +Start a new session with the first agent. With the session-start hook installed by `taskseam setup`, you do not need to ask anything special. The session already contains the SQLite decision and the new deterministic-export constraint. To see only what changed, ask: > Continue this TaskSeam task. Tell me only what changed since you last received it. The response should contain the newly added deterministic-export constraint. +## Correct state + +Tell either agent that a stored item no longer applies, for example: + +> We are dropping the deterministic export requirement. Retire it in TaskSeam. + +The agent proposes `taskseam_retire` with your reason. After approval, `taskseam show` no longer lists it, and other agents receive it as removed. + +If anything does not appear, run `taskseam doctor` in the project folder. + The demo works for any project. The storage topic is example data rather than application logic. Browser capture is a separate developer preview documented in [`browser-extension/README.md`](../browser-extension/README.md). diff --git a/docs/EDITOR_SETUP.md b/docs/EDITOR_SETUP.md index dd6b50a..8097c32 100644 --- a/docs/EDITOR_SETUP.md +++ b/docs/EDITOR_SETUP.md @@ -22,9 +22,12 @@ taskseam init Then restart the editor or begin a new agent chat. Setup also installs a session-start hook, so Claude Code and Codex begin every session with the project's current state without being asked. In Codex, approve the new hook once with `/hooks`. -Check what agents will see at any time: +You do not need the separate `claude` or `codex` command-line tools: setup also finds the copies bundled inside the VS Code, Cursor, and Windsurf extensions. + +Check the connection, and see what agents will receive: ```bash +taskseam doctor taskseam show ``` diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md index 34b7bf7..5987c88 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.md @@ -28,7 +28,7 @@ Run once from any directory: taskseam setup ``` -TaskSeam detects Codex and Claude Code on `PATH` and configures the tools it finds. Missing tools are skipped. +TaskSeam detects Codex and Claude Code on `PATH` or inside the VS Code, Cursor, and Windsurf extensions, so no separate CLI install is needed. It registers the MCP server and installs a session-start hook for each tool it finds. Missing tools are skipped. Codex asks you to trust the new hook once in `/hooks`. ## 3. Initialize a project @@ -39,6 +39,14 @@ taskseam init TaskSeam names the initial task after the project directory, creates `.taskseam/` with a local SQLite database, and adds that directory to `.gitignore`. +## 4. Check the connection + +```bash +taskseam doctor +``` + +Doctor checks each agent's MCP registration and session-start hook, finds the project, and summarizes its state. Each problem it reports comes with the command that fixes it. It also catches the most common mistake: an editor opened on a parent or sibling folder instead of the initialized project. + ## 4. Work normally Open the initialized project in the Codex or Claude Code editor interface and start a new chat. You can also start either agent from the project terminal. diff --git a/plugins/taskseam/.codex-plugin/plugin.json b/plugins/taskseam/.codex-plugin/plugin.json index da7449d..5af379e 100644 --- a/plugins/taskseam/.codex-plugin/plugin.json +++ b/plugins/taskseam/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "taskseam", - "version": "0.2.0", + "version": "0.2.1", "description": "Continue versioned task state across AI agents with local evidence and per-agent deltas.", "author": { "name": "TaskSeam contributors", diff --git a/plugins/taskseam/plugin.json b/plugins/taskseam/plugin.json index df72b1c..c8f3121 100644 --- a/plugins/taskseam/plugin.json +++ b/plugins/taskseam/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "taskseam", - "version": "0.2.0", + "version": "0.2.1", "description": "Continue versioned task state across AI agents with local evidence and per-agent deltas.", "author": { "name": "Sai Sandeep Kantareddy", diff --git a/pyproject.toml b/pyproject.toml index 0c08c42..3b1c31a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "taskseam" -version = "0.2.0" +version = "0.2.1" description = "Local-first task continuity across AI coding agents" readme = "README.md" requires-python = ">=3.9" diff --git a/site/index.html b/site/index.html index 7458cb1..9f09afc 100644 --- a/site/index.html +++ b/site/index.html @@ -60,7 +60,8 @@
Prefer pip? python3 -m pip install taskseam works too.
One-time setup: install, run taskseam setup, then taskseam init in each participating project. Open that project in Codex or Claude Code for VS Code and work through normal conversation.
See it first: taskseam demo runs a one-minute walkthrough in a throwaway folder, with no agents or settings touched.
One-time setup: run taskseam setup, then taskseam init in each participating project. Every new Codex or Claude Code chat then starts with the project's current decisions automatically. Something missing? taskseam doctor shows what to fix.
Local SQLite · Open source · MCP compatible · No hosted account
diff --git a/taskseam/__init__.py b/taskseam/__init__.py index 4729a52..0e3629f 100644 --- a/taskseam/__init__.py +++ b/taskseam/__init__.py @@ -1,3 +1,3 @@ """Local task state and handoff tools.""" -__version__ = "0.2.0" +__version__ = "0.2.1" diff --git a/taskseam/__main__.py b/taskseam/__main__.py index cceebdc..4745cc0 100644 --- a/taskseam/__main__.py +++ b/taskseam/__main__.py @@ -103,6 +103,12 @@ def parser(): destination.add_argument("--agents-md", nargs="?", const="AGENTS.md", metavar="PATH", help="Maintain a TaskSeam block inside AGENTS.md (or PATH)") export.add_argument("--task-id", help="Defaults to the active workspace task") + demo = commands.add_parser("demo", help="One-minute walkthrough in a temporary project") + demo.add_argument("--pause", type=float, default=None, help="Seconds between steps") + doctor = commands.add_parser("doctor", help="Check agent connections and this project's state") + doctor.add_argument("--json", action="store_true", help="Print machine-readable results") + doctor.add_argument("--skip-mcp", action="store_true", + help="Do not ask agent CLIs whether the MCP server is registered") hook = commands.add_parser("hook", help="Agent session hooks") hook_sub = hook.add_subparsers(dest="action", required=True) hook_sub.add_parser("session-start", help="Print state for a SessionStart hook (reads hook JSON)") @@ -119,6 +125,26 @@ def _task_or_active(task_id, workspace): return task_id +def _print_setup_summary(result, dry_run, tool=None): + names = {"claude-code": "Claude Code", "codex": "Codex"} + connected = [{"tool": tool, **result}] if tool else result.get("configured", []) + lines = [] + for entry in connected: + if entry.get("tool"): + how = entry.get("found_via", "") + lines.append(" {} {}{}".format("would connect" if dry_run else "connected", names[entry["tool"]], + " (" + how + ")" if how and how != "PATH" else "")) + for entry in result.get("skipped", []): + lines.append(" skipped {}: {}".format(names.get(entry["tool"], entry["tool"]), entry["reason"])) + for entry in (result.get("session_hooks") or {}).get("hooks", []): + if entry["tool"] == "codex" and entry["status"] != "unchanged": + lines.append(" Codex: open /hooks once and trust the TaskSeam hook") + if lines: + print("\nTaskSeam setup" + (" (dry run, nothing written)" if dry_run else "") + ":\n" + + "\n".join(lines) + "\nNext: cd your-project && taskseam init, then `taskseam doctor`.", + file=sys.stderr) + + def _agents_md_block(task, items): from .render import brief body = brief(task, items, header=False) @@ -129,6 +155,17 @@ def _agents_md_block(task, items): def main(argv=None): args = parser().parse_args(argv) try: + if args.command == "demo": + from .demo import run as run_demo + return run_demo(args.pause) + if args.command == "doctor": + from .doctor import diagnose, render + sections = diagnose(probe_mcp=not args.skip_mcp) + if args.json: + print(json.dumps([{"section": title, "checks": checks} for title, checks in sections], + indent=2)) + return 1 if any(c["status"] == "fail" for _, cs in sections for c in cs) else 0 + return render(sections) if args.command == "hook" and args.action == "session-start": from .hooks import session_start return session_start() @@ -145,6 +182,9 @@ def create_task(path, task_title): root, config = initialize(Path.cwd(), title, create_task) print(json.dumps({"workspace": str(root), "project": config["project"], "active_task": config["active_task"]}, indent=2)) + print("\nTaskSeam is ready in {}.\nNext: open this folder in Claude Code or Codex and " + "start a new chat.\nCheck the connection any time with: taskseam doctor".format(root), + file=sys.stderr) return 0 if args.command == "prompt": from .importer import PACKET_PROMPT @@ -176,6 +216,7 @@ def create_task(path, task_title): tools = {"codex": ["codex"], "claude-code": ["claude-code"]}.get(args.tool) result["session_hooks"] = install_detected(sys.executable, args.dry_run, tools) print(json.dumps(result, indent=2)) + _print_setup_summary(result, args.dry_run, args.tool) return 0 if args.command == "import": from .importer import parse_packet diff --git a/taskseam/demo.py b/taskseam/demo.py new file mode 100644 index 0000000..69ca64d --- /dev/null +++ b/taskseam/demo.py @@ -0,0 +1,94 @@ +"""`taskseam demo`: a one-minute, agent-free walkthrough in a temporary project.""" + +import json +import sys +import tempfile +import time +from pathlib import Path + +from .hooks import session_start +from .render import brief, short +from .store import Store +from .workspace import database_path, find_workspace, initialize + + +def run(pause=None, stream=None): + stream = stream or sys.stdout + color = hasattr(stream, "isatty") and stream.isatty() + if pause is None: + pause = 1.2 if color else 0.0 + + def say(text): + stream.write("\n" + ("\033[1m# " + text + "\033[0m" if color else "# " + text) + "\n") + stream.flush() + time.sleep(pause) + + def show(text): + stream.write(text if text.endswith("\n") else text + "\n") + stream.flush() + + with tempfile.TemporaryDirectory(prefix="taskseam-demo-") as directory: + root = Path(directory) + + def create(path, title): + store = Store(path) + try: + return store.create_task(title) + finally: + store.close() + + initialize(root, "Invoice exporter", create) + workspace = find_workspace(root) + task = workspace[1]["active_task"] + store = Store(database_path(workspace)) + try: + say("Monday, in Claude Code: you accept a decision, and the agent saves it") + pdf = store.add_item(task, "decision", "Export invoices as PDF", "claude-code") + store.add_item(task, "constraint", "Never send invoice data to third-party services", "user") + store.add_item(task, "question", "Should exports include voided invoices?", "claude-code") + store.handoff(task, "claude-code") + context = store.context(task) + show(brief(context["task"], context["items"], header=False, ids=False)) + + say("Tuesday, in Codex: you change your mind. CSV replaces PDF, plus a new rule") + csv = store.add_item(task, "decision", "Export invoices as CSV, not PDF", "codex", pdf) + store.add_item(task, "constraint", "CSV must follow RFC 4180", "codex") + show("saved. The PDF decision is superseded, not deleted") + + say("Any new chat, in any agent: the session-start hook loads current state") + show("(no prompting, no pasted history. The old PDF decision is gone)") + stdin = _Input(json.dumps({"cwd": str(root), "source": "startup"})) + session_start(stdin, stream) + + say("Back in Claude Code: it receives only what changed since its last visit") + delta = store.handoff(task, "claude-code") + for item in delta["added"]: + show(" + {}: {}".format(item["kind"], item["body"])) + for item in delta["removed"]: + show(" - {}: {}".format(item["kind"], item["body"])) + + say("Every item keeps its evidence") + evidence = store.explain(csv) + show(" {} `{}` <- {} at {}".format(evidence["body"], short(csv), evidence["source"], + evidence["event_time"][:16].replace("T", " "))) + finally: + store.close() + + say("Try it in your own project") + show(" taskseam setup # connect Claude Code and Codex (CLI or editor extension)\n" + " cd your-project && taskseam init\n" + " taskseam doctor # confirm everything is connected") + return 0 + + +class _Input: + """Minimal stdin stand-in for the hook (not a TTY).""" + + def __init__(self, text): + self.text = text + + def isatty(self): + return False + + def read(self): + return self.text diff --git a/taskseam/doctor.py b/taskseam/doctor.py new file mode 100644 index 0000000..343b7b9 --- /dev/null +++ b/taskseam/doctor.py @@ -0,0 +1,177 @@ +"""`taskseam doctor`: explain exactly what is connected and how to fix what is not.""" + +import json +import shlex +import subprocess +import sys +from pathlib import Path + +from . import __version__ +from .hooks import HOOK_MARKER, claude_settings_path, codex_hooks_path +from .setup import find_agent +from .store import SCHEMA_VERSION, Store +from .workspace import active_task, database_path, find_workspace + +AGENTS = (("Claude Code", "claude-code", "claude", claude_settings_path), + ("Codex", "codex", "codex", codex_hooks_path)) + + +def _check(status, name, detail, fix=None): + return {"status": status, "check": name, "detail": detail, "fix": fix} + + +def _mcp_registration(executable, tool): + try: + result = subprocess.run([executable, "mcp", "get", "taskseam"], capture_output=True, + text=True, timeout=30) + except (OSError, subprocess.TimeoutExpired) as exc: + return _check("warn", "MCP server", "could not ask {}: {}".format(tool, exc)) + if result.returncode != 0: + return _check("fail", "MCP server", "taskseam is not registered", + "taskseam setup " + tool) + output = result.stdout + result.stderr + if "taskseam" in output and sys.executable not in output and "-m taskseam" in output: + return _check("warn", "MCP server", + "registered with a different Python than this TaskSeam ({})".format(sys.executable), + "taskseam setup " + tool) + return _check("ok", "MCP server", "registered") + + +def _hook(path, tool): + if not path.exists(): + return _check("fail", "Session-start hook", "not installed ({} missing)".format(path), + "taskseam hook install " + tool) + try: + data = json.loads(path.read_text(encoding="utf-8") or "{}") + except (OSError, ValueError) as exc: + return _check("fail", "Session-start hook", "cannot read {}: {}".format(path, exc)) + groups = ((data.get("hooks") or {}).get("SessionStart") or []) if isinstance(data, dict) else [] + for group in groups: + for handler in (group.get("hooks") or []) if isinstance(group, dict) else []: + command = str(handler.get("command", "")) if isinstance(handler, dict) else "" + if HOOK_MARKER not in command: + continue + try: + python = shlex.split(command)[0] + except (ValueError, IndexError): + python = "" + if python and not Path(python).exists(): + return _check("fail", "Session-start hook", + "points to a Python that no longer exists: " + python, + "taskseam hook install " + tool) + detail = "installed in " + str(path) + if tool == "codex": + detail += "; Codex runs it after you trust it once in /hooks" + return _check("ok", "Session-start hook", detail) + return _check("fail", "Session-start hook", "not installed in " + str(path), + "taskseam hook install " + tool) + + +def _nearby_workspaces(cwd, limit=3): + found = [] + try: + for config in sorted(cwd.glob("*/.taskseam/config.json")) + sorted(cwd.glob("*/*/.taskseam/config.json")): + found.append(str(config.parent.parent)) + if len(found) >= limit: + break + except OSError: + pass + return found + + +def _project(cwd): + checks = [] + try: + workspace = find_workspace(cwd) + except ValueError as exc: + return [_check("fail", "Project", str(exc))] + if not workspace: + nearby = _nearby_workspaces(cwd) + if nearby: + return [_check("fail", "Project", + "{} is not inside a TaskSeam project, but these folders are: {}. Agents " + "only see state when the editor opens the project folder itself.".format( + cwd, ", ".join(nearby)), + "open one of those folders in your editor, or cd into it")] + return [_check("fail", "Project", "{} is not inside a TaskSeam project".format(cwd), + "cd your-project && taskseam init")] + root = workspace[0] + checks.append(_check("ok", "Project", str(root))) + try: + store = Store(database_path(workspace)) + try: + version = store.db.execute("PRAGMA user_version").fetchone()[0] + context = store.context(active_task(workspace)) + finally: + store.close() + except (ValueError, OSError) as exc: + checks.append(_check("fail", "Project state", str(exc))) + return checks + counts = {} + for item in context["items"]: + counts[item["kind"]] = counts.get(item["kind"], 0) + 1 + summary = ", ".join("{} {}{}".format(counts.get(kind, 0), kind, "" if counts.get(kind, 0) == 1 else "s") + for kind in ("decision", "constraint", "question")) + checks.append(_check("ok", "Project state", + "task '{}' (schema v{}): {}".format(context["task"]["title"], version, summary))) + if version != SCHEMA_VERSION: + checks.append(_check("warn", "Project state", "schema v{} differs from v{}".format( + version, SCHEMA_VERSION))) + if not context["items"]: + checks.append(_check("warn", "Project state", + "nothing recorded yet; agents save state when you accept a decision", + 'taskseam record decision "..." --source user')) + ignore = root / ".gitignore" + lines = ignore.read_text(encoding="utf-8").splitlines() if ignore.exists() else [] + if not {".taskseam/", "/.taskseam/", ".taskseam"} & {line.strip() for line in lines}: + checks.append(_check("warn", "Privacy", ".taskseam/ is not in .gitignore, so state could be committed", + "echo '.taskseam/' >> .gitignore")) + return checks + + +def diagnose(cwd=None, probe_mcp=True): + cwd = Path(cwd or Path.cwd()).resolve() + sections = [("TaskSeam", [_check("ok", "Installed", "{} ({})".format(__version__, sys.executable))])] + any_agent = False + for label, tool, executable, locate in AGENTS: + found, how = find_agent(executable) + if not found: + sections.append((label, [_check("info", "Installed", "not found on PATH or in an editor extension")])) + continue + any_agent = True + checks = [_check("ok", "Installed", "{} ({})".format(found, how))] + if probe_mcp: + checks.append(_mcp_registration(found, tool)) + checks.append(_hook(locate(), tool)) + sections.append((label, checks)) + if not any_agent: + sections[0][1].append(_check("fail", "Agents", "neither Claude Code nor Codex was found", + "install Claude Code or Codex, then run taskseam setup")) + sections.append(("This folder", _project(cwd))) + return sections + + +SYMBOLS = {"ok": ("✓", "ok"), "warn": ("!", "!!"), "fail": ("✗", "XX"), "info": ("-", "--")} + + +def render(sections, stream=None): + stream = stream or sys.stdout + encoding = getattr(stream, "encoding", None) or "utf-8" + try: + "✓✗".encode(encoding) + index = 0 + except (UnicodeEncodeError, LookupError): + index = 1 + lines = [] + for title, checks in sections: + lines.append(title) + for check in checks: + lines.append(" {} {}: {}".format(SYMBOLS[check["status"]][index], check["check"], check["detail"])) + if check["fix"] and check["status"] in ("fail", "warn"): + lines.append(" fix: " + check["fix"]) + lines.append("") + problems = sum(1 for _, checks in sections for check in checks if check["status"] == "fail") + lines.append("Everything needed is in place." if not problems else + "{} problem{} found.".format(problems, "" if problems == 1 else "s")) + stream.write("\n".join(lines) + "\n") + return 1 if problems else 0 diff --git a/taskseam/hooks.py b/taskseam/hooks.py index e74311a..57ddfdb 100644 --- a/taskseam/hooks.py +++ b/taskseam/hooks.py @@ -8,12 +8,12 @@ import json import os -import shutil import subprocess import sys from pathlib import Path from .render import brief +from .setup import find_agent from .store import Store from .workspace import active_task, database_path, find_workspace @@ -135,8 +135,8 @@ def install_detected(python_executable=None, dry_run=False, tools=None): for name, executable, locate in targets: if tools and name not in tools: continue - if not shutil.which(executable): - skipped.append({"tool": name, "reason": "not found on PATH"}) + if not find_agent(executable)[0] and not locate().parent.is_dir(): + skipped.append({"tool": name, "reason": "not installed"}) continue result = install(locate(), python_executable, dry_run) if name == "codex": diff --git a/taskseam/setup.py b/taskseam/setup.py index 71971fd..5206bd5 100644 --- a/taskseam/setup.py +++ b/taskseam/setup.py @@ -1,22 +1,59 @@ """Configuration helpers for supported AI tools.""" +import os +import re import shutil import subprocess import sys +from pathlib import Path + +# Editor extensions bundle their own agent CLI. Users who only install the +# VS Code/Cursor extension have no `claude` or `codex` on PATH. +EDITOR_EXTENSION_DIRS = (".vscode/extensions", ".vscode-insiders/extensions", + ".cursor/extensions", ".windsurf/extensions") +BUNDLED = { + "claude": ("anthropic.claude-code-*", ("resources/native-binary/claude", + "resources/native-binary/claude.exe")), + "codex": ("openai.chatgpt-*", ("bin/*/codex", "bin/*/codex.exe")), +} + + +def _version_key(path): + match = re.search(r"-(\d+(?:\.\d+)*)", path.name) + return tuple(int(part) for part in match.group(1).split(".")) if match else () + + +def find_agent(name, home=None): + """Return (executable, how_found) for an agent CLI, or (None, None).""" + on_path = shutil.which(name) + if on_path: + return on_path, "PATH" + pattern, binaries = BUNDLED[name] + home = Path(home or Path.home()) + candidates = [] + for base in EDITOR_EXTENSION_DIRS: + for extension in (home / base).glob(pattern): + for binary in binaries: + candidates.extend((extension, found) for found in extension.glob(binary) + if found.is_file() and os.access(str(found), os.X_OK)) + if not candidates: + return None, None + extension, found = max(candidates, key=lambda pair: _version_key(pair[0])) + return str(found), "editor extension " + extension.name def codex_command(python_executable=None): - codex = shutil.which("codex") + codex = find_agent("codex")[0] if not codex: - raise ValueError("Codex CLI was not found on PATH") + raise ValueError("Codex was not found on PATH or in a VS Code/Cursor extension") python = python_executable or sys.executable return [codex, "mcp", "add", "taskseam", "--", python, "-m", "taskseam", "mcp"] def claude_command(python_executable=None): - claude = shutil.which("claude") + claude = find_agent("claude")[0] if not claude: - raise ValueError("Claude Code CLI was not found on PATH") + raise ValueError("Claude Code was not found on PATH or in a VS Code/Cursor extension") python = python_executable or sys.executable return [claude, "mcp", "add", "--scope", "user", "taskseam", "--", python, "-m", "taskseam", "mcp"] @@ -68,10 +105,12 @@ def setup_detected(python_executable=None, dry_run=False): skipped = [] for name, installer in installers: executable = "claude" if name == "claude-code" else name - if not shutil.which(executable): - skipped.append({"tool": name, "reason": "not found on PATH"}) + found, how = find_agent(executable) + if not found: + skipped.append({"tool": name, + "reason": "not found on PATH or in a VS Code/Cursor extension"}) continue result = installer(python_executable, dry_run) - detected.append({"tool": name, **result}) + detected.append({"tool": name, "found_via": how, **result}) return {"configured": detected, "skipped": skipped, "web_assistants": "ChatGPT and Claude web support is available as a developer-preview browser extension"} diff --git a/tests/test_doctor.py b/tests/test_doctor.py new file mode 100644 index 0000000..af81902 --- /dev/null +++ b/tests/test_doctor.py @@ -0,0 +1,117 @@ +import io +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from taskseam import doctor, hooks + +ROOT = Path(__file__).resolve().parents[1] + + +def statuses(sections): + return {(title, check["check"]): check["status"] for title, checks in sections for check in checks} + + +class DoctorTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.claude = self.root / "home" / ".claude" / "settings.json" + self.codex = self.root / "home" / ".codex" / "hooks.json" + patches = [ + mock.patch("taskseam.doctor.AGENTS", ( + ("Claude Code", "claude-code", "claude", lambda: self.claude), + ("Codex", "codex", "codex", lambda: self.codex))), + mock.patch("taskseam.doctor.find_agent", + side_effect=lambda name: ("/bin/" + name, "PATH") if name == "claude" else (None, None)), + ] + for patch in patches: + patch.start() + self.addCleanup(patch.stop) + + def tearDown(self): + self.tmp.cleanup() + + def init_project(self, name="project"): + project = self.root / name + project.mkdir() + subprocess.run([sys.executable, "-m", "taskseam", "init"], cwd=project, check=True, + capture_output=True, env={**os.environ, "PYTHONPATH": str(ROOT)}) + return project + + def test_healthy_setup_reports_no_problems(self): + hooks.install(self.claude, sys.executable) + project = self.init_project() + registered = mock.Mock(returncode=0, stdout=sys.executable + " -m taskseam mcp", stderr="") + with mock.patch("taskseam.doctor.subprocess.run", return_value=registered): + sections = doctor.diagnose(project) + result = statuses(sections) + self.assertEqual(result[("Claude Code", "MCP server")], "ok") + self.assertEqual(result[("Claude Code", "Session-start hook")], "ok") + self.assertEqual(result[("Codex", "Installed")], "info") + self.assertEqual(result[("This folder", "Project")], "ok") + out = io.StringIO() + self.assertEqual(doctor.render(sections, out), 0) + self.assertIn("Everything needed is in place", out.getvalue()) + + @mock.patch("taskseam.doctor.subprocess.run") + def test_missing_registration_hook_and_stale_python_have_fixes(self, run): + run.return_value = mock.Mock(returncode=1, stdout="", stderr="not found") + sections = doctor.diagnose(self.root) + result = statuses(sections) + self.assertEqual(result[("Claude Code", "MCP server")], "fail") + self.assertEqual(result[("Claude Code", "Session-start hook")], "fail") + hooks.install(self.claude, "/gone/python") + stale = [c for t, cs in doctor.diagnose(self.root, probe_mcp=False) for c in cs + if c["check"] == "Session-start hook"][0] + self.assertIn("no longer exists", stale["detail"]) + self.assertEqual(stale["fix"], "taskseam hook install claude-code") + out = io.StringIO() + self.assertEqual(doctor.render(sections, out), 1) + self.assertIn("fix: taskseam setup claude-code", out.getvalue()) + + def test_wrong_folder_points_to_nearby_projects(self): + self.init_project("app") + project = [c for t, cs in doctor.diagnose(self.root, probe_mcp=False) for c in cs + if c["check"] == "Project"][0] + self.assertEqual(project["status"], "fail") + self.assertIn(str(self.root / "app"), project["detail"]) + + def test_privacy_warning_when_state_is_not_ignored(self): + project = self.init_project() + (project / ".gitignore").write_text("node_modules/\n") + result = statuses(doctor.diagnose(project, probe_mcp=False)) + self.assertEqual(result[("This folder", "Privacy")], "warn") + + def test_ascii_fallback_for_limited_consoles(self): + class Ascii(io.StringIO): + encoding = "ascii" + out = Ascii() + doctor.render([("X", [doctor._check("fail", "Thing", "broken", "fix it")])], out) + self.assertIn("XX Thing", out.getvalue()) + + +class DemoTests(unittest.TestCase): + def test_demo_tells_the_story_and_cleans_up(self): + from taskseam.demo import run + out = io.StringIO() + with mock.patch("taskseam.demo.tempfile.TemporaryDirectory", + wraps=tempfile.TemporaryDirectory) as temporary: + self.assertEqual(run(pause=0, stream=out), 0) + text = out.getvalue() + self.assertIn("+ decision: Export invoices as CSV, not PDF", text) + self.assertIn("- decision: Export invoices as PDF", text) + hook_part = text.split("session-start hook")[1].split("Back in Claude Code")[0] + self.assertNotIn("Export invoices as PDF\n", hook_part) + self.assertIn("RFC 4180", hook_part) + created = temporary.call_args.kwargs.get("prefix") + self.assertEqual(created, "taskseam-demo-") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_setup.py b/tests/test_setup.py index 4f37cb5..4ef356c 100644 --- a/tests/test_setup.py +++ b/tests/test_setup.py @@ -1,7 +1,10 @@ +import os +import tempfile import unittest +from pathlib import Path from unittest import mock -from taskseam.setup import (claude_command, codex_command, setup_claude, +from taskseam.setup import (claude_command, codex_command, find_agent, setup_claude, setup_codex, setup_detected) @@ -47,15 +50,45 @@ def test_setup_claude_adds_server(self, _which, run): @mock.patch("taskseam.setup.setup_claude") @mock.patch("taskseam.setup.setup_codex") - @mock.patch("taskseam.setup.shutil.which") - def test_auto_setup_configures_only_detected_tools(self, which, codex, claude): - which.side_effect = lambda name: "/tools/codex" if name == "codex" else None + @mock.patch("taskseam.setup.find_agent") + def test_auto_setup_configures_only_detected_tools(self, find, codex, claude): + find.side_effect = lambda name: ("/tools/codex", "PATH") if name == "codex" else (None, None) codex.return_value = {"configured": True} result = setup_detected("/venv/bin/python") - self.assertEqual(result["configured"], [{"tool": "codex", "configured": True}]) + self.assertEqual(result["configured"], + [{"tool": "codex", "found_via": "PATH", "configured": True}]) self.assertEqual(result["skipped"][0]["tool"], "claude-code") claude.assert_not_called() +class FindAgentTests(unittest.TestCase): + def make_binary(self, path): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("#!/bin/sh\n") + os.chmod(str(path), 0o755) + + @mock.patch("taskseam.setup.shutil.which", return_value=None) + def test_finds_newest_bundled_editor_binary(self, _which): + with tempfile.TemporaryDirectory() as home: + ext = Path(home) / ".vscode" / "extensions" + self.make_binary(ext / "anthropic.claude-code-2.1.9-darwin-arm64" / + "resources" / "native-binary" / "claude") + newest = (Path(home) / ".cursor" / "extensions" / + "anthropic.claude-code-2.1.10-darwin-arm64" / "resources" / "native-binary" / "claude") + self.make_binary(newest) + self.make_binary(ext / "openai.chatgpt-26.1117.4-darwin-arm64" / "bin" / "macos-aarch64" / "codex") + found, how = find_agent("claude", home) + self.assertEqual(found, str(newest)) + self.assertIn("2.1.10", how) + self.assertTrue(find_agent("codex", home)[0].endswith("codex")) + + @mock.patch("taskseam.setup.shutil.which", return_value="/usr/local/bin/claude") + def test_path_wins_and_missing_returns_none(self, _which): + self.assertEqual(find_agent("claude"), ("/usr/local/bin/claude", "PATH")) + with mock.patch("taskseam.setup.shutil.which", return_value=None), \ + tempfile.TemporaryDirectory() as home: + self.assertEqual(find_agent("codex", home), (None, None)) + + if __name__ == "__main__": unittest.main()