diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 861d4ef..d904212 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,12 +11,14 @@ permissions: jobs: test: strategy: + fail-fast: false matrix: python-version: ["3.9", "3.11", "3.13"] - runs-on: ubuntu-latest + # ubuntu-latest (26.04) no longer provides Python 3.9, which macOS still ships as python3. + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v5 + - uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} - run: python -m unittest discover -s tests -v @@ -26,8 +28,8 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v5 + - uses: actions/setup-python@v6 with: python-version: "3.11" - run: python -m pip install build twine diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 28c7085..659f4cb 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -12,10 +12,10 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: persist-credentials: false - - uses: actions/setup-python@v5 + - uses: actions/setup-python@v6 with: python-version: "3.11" - run: python -m pip install build twine diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f5baeb..6d02e19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,27 @@ All notable changes to TaskSeam will be documented here. +## 0.2.0 - 2026-11-21 + +Upgrade with `pipx upgrade taskseam` (or `python3 -m pip install -U taskseam`), then rerun +`taskseam setup` to install the session-start hook. Databases upgrade to schema version 4 +automatically; once upgraded, they cannot be opened by 0.1.x. + +- Add optional full current-state recovery to MCP continuation and CLI handoff + for fresh chats and lost context, preserving normal per-target deltas. +- Add recovery regression coverage and an evidence-linked next-step research memo. +- Load project state automatically: `taskseam setup` installs a read-only SessionStart hook + for Claude Code and Codex (`--no-hooks` to skip; `taskseam hook install` to manage it). +- Add `taskseam show`, a readable view of the state agents receive. +- Add `taskseam drop` and the `taskseam_retire` MCP tool. They remove an item that no longer + applies, recording the reason as an event. The database schema moves to version 4. +- Add deterministic `taskseam export` (JSON with optional history, or Markdown) and + `--agents-md`, which maintains a marked block in AGENTS.md for agents without MCP. +- Accept unique item ID prefixes in the CLI and MCP tools. +- MCP: negotiate protocol revisions 2025-11-25, 2025-06-18, and 2025-03-26; return + `structuredContent`; add a `continue` prompt and a current-state resource. +- Briefs with a size budget report omitted item counts instead of truncating silently. + ## 0.1.1 - 2026-09-24 - Use the public PyPI installation command throughout the onboarding experience. diff --git a/README.md b/README.md index 5c6072a..761bbd5 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,20 @@ Start with this prompt: > Continue this project. What accepted decisions, constraints, and open questions should I know? -There are no routine TaskSeam commands after initialization. +There are no routine TaskSeam commands after initialization. In Claude Code and Codex, `taskseam setup` installs a session-start hook, so each new chat starts with the project's state even before you ask. Codex asks you to trust the hook once in `/hooks`. + +## Everyday commands + +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 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 +taskseam export --history # deterministic JSON, including superseded items +``` + +Item IDs accept any unique prefix of four or more characters. ## What changes for the user? @@ -126,11 +139,11 @@ The [five-minute demo](https://github.com/TaskSeam/taskseam/blob/main/docs/DEMO. The [public roadmap](https://github.com/TaskSeam/taskseam/blob/main/ROADMAP.md) tracks the current priorities: -1. Validate clean installation across supported operating systems. -2. Publish the Python package to PyPI. -3. Package and submit the browser extension. -4. Improve automatic task matching and correction. -5. Publish repeatable continuity evaluations. +1. Retry-safe delivery: acknowledge exactly what an agent received. +2. Publish repeatable continuity evaluations. +3. Validate clean installation across supported operating systems. +4. Package and submit the browser extension. +5. Improve automatic task matching and correction. ## Development diff --git a/ROADMAP.md b/ROADMAP.md index bd79b6c..b4191a9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,6 +2,17 @@ TaskSeam aims to provide versioned task state across AI tools. This roadmap defines the behavior required to distinguish that product from a generic memory store or transcript handoff. +## Proposed next priorities + +The [October 2026 ecosystem review](docs/NEXT_STEPS_RESEARCH.md) recommends: + +1. Reliable fresh-chat recovery (released in 0.2.0 with session-start hooks), followed by retry-safe delivery. +2. Reproducible evaluations against transcripts, summaries, maintained Markdown, and memory retrieval. +3. Deterministic exports, auditable corrections, and concurrent-write protection. +4. Budgeted delivery with explicit omissions, then demand-led integrations. + +These are recommendations; the research memo separates implemented behavior from future work. + ## North-star acceptance scenario 1. A user discusses a feature in ChatGPT and considers storing state in Markdown. @@ -30,7 +41,9 @@ TaskSeam is ready for a broader alpha when this scenario works repeatedly on an - [x] Localhost API - [x] MCP delivery with approved state updates - [ ] Schema migrations with compatibility tests + - Version-one migration has a regression test; broader compatibility coverage remains. - [ ] Export and deletion commands + - Deterministic JSON/Markdown export and item retirement shipped in 0.2.0; whole-task deletion remains. ## Milestone 2: Evidence ingestion @@ -55,7 +68,10 @@ TaskSeam is ready for a broader alpha when this scenario works repeatedly on an - [x] Record the checkpoint last delivered to each tool - [x] Generate a delta from that checkpoint - [ ] Filter by target, purpose, permissions, and token budget -- [ ] Deliver the result through MCP +- [x] Deliver the result through MCP +- [x] Optional full current-state recovery for fresh chats +- [x] Session-start hooks that inject current state in Claude Code and Codex +- [ ] Acknowledge exact snapshots after successful delivery, with retry and concurrency tests - [ ] Preview and approve sensitive handoffs - [ ] Package a Claude Desktop extension with explicit project selection diff --git a/docs/EDITOR_SETUP.md b/docs/EDITOR_SETUP.md index b176e94..dd6b50a 100644 --- a/docs/EDITOR_SETUP.md +++ b/docs/EDITOR_SETUP.md @@ -20,7 +20,13 @@ cd your-project taskseam init ``` -Then restart the editor or begin a new agent chat. +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: + +```bash +taskseam show +``` ## Codex in VS Code or Cursor diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md index f8feb13..1fce851 100644 --- a/docs/INTEGRATIONS.md +++ b/docs/INTEGRATIONS.md @@ -44,3 +44,71 @@ Other AI clients require local MCP support or a dedicated TaskSeam adapter. They Claude Desktop uses a separate desktop-extension system and does not automatically inherit Claude Code's project working directory. TaskSeam does not currently present it as supported. A packaged desktop extension with an explicit project selector is planned. See the [editor setup guide](EDITOR_SETUP.md) for the complete interface matrix. + +## Load state automatically at session start + +`taskseam setup` also installs a read-only SessionStart hook for Claude Code +(`~/.claude/settings.json`) and Codex (`~/.codex/hooks.json`, or `$CODEX_HOME`). +Both hosts add the hook's output to the model's context. Every new, resumed, +cleared, or compacted session therefore starts with the project's accepted +decisions, active constraints, and open questions, even if the model never +calls a TaskSeam tool. + +- The hook prints nothing outside an initialized project and never blocks a session. +- It does not advance any agent's delivery position, so `taskseam_continue` deltas are unaffected. +- Output stays under 6,000 characters, below both hosts' limits. Items that do not fit are + counted explicitly rather than silently dropped. +- Codex runs a new hook only after you review and trust it with `/hooks`. +- Existing settings are preserved. A one-time `*.taskseam-backup` copy is written beside the file. + +Install or refresh only the hook with `taskseam hook install [claude-code|codex]`, +preview the change with `--dry-run`, or skip it during setup with `taskseam setup --no-hooks`. + +## MCP prompt and resource + +Besides its tools, the MCP server exposes: + +- a `continue` prompt. Claude Code shows it as `/mcp__taskseam__continue`, which loads state on demand; +- a `taskseam://active/brief` Markdown resource with the current state. + +The server negotiates MCP protocol revisions 2025-11-25, 2025-06-18, and 2025-03-26, +and tool results include `structuredContent` alongside the JSON text. + +## Agents without MCP: AGENTS.md + +Agents that read `AGENTS.md` but cannot reach TaskSeam (Cursor rules, Gemini CLI, +Jules, Windsurf, and others) can receive a generated copy of the current state: + +```bash +taskseam export --agents-md # or --agents-md docs/AGENTS.md +``` + +TaskSeam maintains only the block between `` and +``. The rest of the file is left untouched, and rerunning the +command replaces the block. `AGENTS.md` is usually committed, so review the block +before pushing. Your state then leaves the private `.taskseam/` directory. + +Other exports are deterministic: + +```bash +taskseam export # current state as JSON (schema "taskseam_export": 1) +taskseam export --history # include superseded, resolved, and retired items +taskseam export --format markdown -o STATE.md +``` + +## Recover state in a fresh chat + +In a fresh chat or after losing prior context, call `taskseam_continue` with +`{"target": "codex", "full": true}` (use the receiving agent's stable target name). +In an initialized workspace the task is inferred; otherwise supply `task_id`. +The CLI equivalent is: + +```bash +taskseam handoff --to codex --full +``` + +`current` contains all current items, while `added` and `removed` remain the +changes since that target's previous delivery. `changed: false` means no new +changes, not an empty task. Ordinary continuation omits `current` to keep +responses small. Recovery does not reset other agents' delivery positions. +This option requires TaskSeam 0.2.0 or later. diff --git a/docs/NEXT_STEPS_RESEARCH.md b/docs/NEXT_STEPS_RESEARCH.md new file mode 100644 index 0000000..1d5c37a --- /dev/null +++ b/docs/NEXT_STEPS_RESEARCH.md @@ -0,0 +1,99 @@ +# TaskSeam: next steps from ecosystem research + +Reviewed October 20, 2026. Recommendations are proposals, not accepted product decisions. This review does not independently reproduce competitors' benchmarks or establish customer demand. + +## Recommendation + +Prioritize reliable continuation across fresh sessions, then prove its value with reproducible evaluations. TaskSeam's strongest product hypothesis is a small, inspectable record of accepted decisions, active constraints, unresolved questions, and what changed between independent tools. + +“Agents have memory” is already a crowded category. Local storage, MCP support, and multiple client integrations alone are insufficient differentiation. The opportunity is whether users can trust the state carried across a switch, correct it easily, and spend less time repeating themselves. + +## External signals and practical responses + +| Signal and primary evidence | Implication | Recommended response | +|---|---|---| +| GitHub describes repository-scoped memory shared across coding agent, CLI, and review, with citation verification. [GitHub engineering, January 15, 2026](https://github.blog/ai-and-ml/github-copilot/building-an-agentic-memory-system-for-github-copilot/) | Built-in memory is a serious alternative. Provenance also exists elsewhere. | Demonstrate accepted-state correctness across independent hosts; add artifact freshness checks rather than claiming provenance alone is unique. | +| Anthropic describes continuity failures between context windows and uses progress artifacts and incremental verification. [Long-running harnesses, November 26, 2025](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents) | A tool identity is not a session identity. Delivery yesterday does not imply knowledge in today's chat. | Recover current state on a fresh chat, retain deltas for continuation, and test context loss explicitly. | +| Anthropic treats context as finite; Agent Skills specifies progressive loading. [Context engineering](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents), [Skills specification](https://agentskills.io/specification) | History injection is costly, but blindly shrinking state can hide constraints. | Keep concise state and on-demand evidence; introduce budgeted pagination with explicit omissions and delivery accounting. | +| Agent HQ describes coordination across multiple agent providers through a common development platform. [GitHub announcement](https://github.blog/news-insights/company-news/welcome-home-agents/) | Switching may increasingly occur within platforms as well as between them. | Integrate with existing workflows; test independent-host handoffs as a distinct use case. This announcement establishes direction, not current availability of every announced integration. | +| Letta provides persistent, shared, optionally read-only memory blocks and documents concurrent overwrite behavior. [Letta memory blocks](https://docs.letta.com/v1-sdk/memory/memory-blocks) | Structured state and cross-agent sharing are established capabilities. | Evaluate explicit supersession, correction history, and recipient state. Address concurrent writes before team sync. | +| Mem0 documents graph-based entity and relationship retrieval. [Mem0 graph memory](https://docs.mem0.ai/platform/features/graph-memory) | Retrieval can supply useful evidence, but relevance is not user acceptance. | Consider memory adapters as evidence inputs; require review before promoting retrieved claims into accepted state. | +| Agentmemory advertises local memory, MCP integrations, and reproducible retrieval evaluations. [Project repository](https://github.com/rohitg00/agentmemory) | Open-source alternatives overlap with the local, multi-tool positioning. | Compare identical continuation scenarios. Its author-reported results cannot establish a TaskSeam performance advantage. | +| MCP's Tasks extension describes durable execution and deferred result retrieval. [Draft specification](https://tasks.extensions.modelcontextprotocol.io/specification/draft/tasks) | Protocol execution tasks and TaskSeam's accepted work state solve different problems. | Keep ordinary tools for local reads/writes. Consider asynchronous support only for long-running imports; do not conflate task identifiers or imply extension support. | + +## Repository findings + +The store implements explicit supersession, question resolution, source-event lookup, checkpoints, per-target deltas, and a version-one migration test. MCP exposes continuation and writes. Browser ingestion is a reviewed packet workflow, not reliable arbitrary conversation reconstruction. + +Documentation needed narrower claims: + +- The roadmap left MCP delivery unchecked although it exists. +- Migration exists, but broad legacy-version and corrupted-database coverage remains. +- The article called history append-only, although `set_supersession` updates an existing relationship. +- Approval is host behavior and agent guidance; MCP annotations do not independently enforce acceptance. +- Source and evidence are recorded assertions, not authenticated proof of human acceptance. + +The checkout has a demo database but no active workspace configuration. The connected tool could not supply active task state; demo content was not treated as accepted project guidance. + +## Implemented improvement + +Previously, a new chat using an already-used target could receive an empty delta and no current state. Optional `full=true` in MCP continuation and `handoff --full` in the CLI now return a `current` array alongside the normal delta. + +Use full recovery in a fresh chat or after losing prior context. Within an ongoing session, leave it off. `changed` still describes changes since the previous delivery; it can be false while `current` contains state. Recovery excludes superseded decisions and resolved questions, preserves source references, and leaves other targets' positions alone. + +This is explicit recovery, not automatic session detection or acknowledged delivery. The cursor still advances before the caller confirms receipt. A host that never requests full recovery can still begin with insufficient context. + +## Proposed sequence and acceptance gates + +### 1. Continuation reliability + +Release recovery after normal review. Next, design preview/acknowledgment so a dropped response does not consume unseen changes. An acknowledgment must identify the exact delivered snapshot and must not move a newer cursor backward. + +Acceptance gate: restart, retry, lost response, out-of-order acknowledgment, two recipients, and an empty task have defined results. Preserve older clients' default behavior. + +Improve workspace diagnostics too: distinguish an uninitialized repository from a host launched in the wrong directory. Offer explicit task selection rather than guessing from similar conversation text. + +### 2. Reproducible continuation evaluations + +Publish synthetic scenarios with explicit gold state: + +1. Replace a decision twice while preserving provenance. +2. Resolve one question while another remains open. +3. Resume two recipients from different checkpoints. +4. Start a fresh chat with an unchanged recipient cursor. +5. Include an unrelated task with matching vocabulary. +6. Include malicious instructions in source evidence. +7. Correct an incorrectly linked supersession. +8. Interrupt delivery and retry. + +Separate deterministic store correctness from model behavior. Compare full transcript, maintained Markdown state, latest-session summary, shared-memory retrieval, and TaskSeam with identical inputs and model settings. Maintained Markdown matters: it is a cheap, credible alternative. + +Report current-decision precision/recall, unresolved-question recall, stale-item inclusion, provenance correctness, cross-task leakage, output tokens using a named tokenizer, latency, and user corrections. Repeat model runs and disclose failures. The regression tests added here are not a model benchmark and do not prove token savings. + +### 3. Inspectable, correctable state + +Add deterministic JSON/Markdown exports with a schema version and source references. Distinguish current-state exports from full history; omit raw evidence by default when sharing. Specify deletion separately from supersession. + +Record lineage corrections as events before promising immutable history. Add expected-version checks or serialization for competing writes. Recheck applicability when branch/worktree or referenced artifacts change; do not automatically expire accepted decisions merely because they are old. + +Acceptance gate: identical state produces identical exports, corrections remain explainable, and two writers cannot silently replace the same current item. + +### 4. Bounded delivery and integrations + +Define a byte/item budget before claiming a universal token budget. Return omitted counts and a continuation handle; never advance a recipient past omitted items. Preserve removal information so recipients can discard stale state. + +Prioritize adapters from observed demand. Test two independent coding hosts first. Browser capture should retain review and correction. Team/cloud sync should wait for permission, identity, conflict, and deletion semantics. + +## Validate the product before expanding scope + +Recruit a small opt-in pilot of developers already switching between at least two agents. Observe several switches per developer, including fresh chats and changed decisions. Measure time to resume, repeated explanation, incorrect carried state, correction effort, and voluntary reuse. + +Proceed when developers repeatedly choose TaskSeam over maintained notes and resume correctly. If they rarely switch, or maintaining accepted state costs more effort than it saves, revise the hypothesis before adding connectors. + +Defer autonomous extraction, vector-search infrastructure, hosted accounts, and a general orchestrator until evidence supports them. Each would substantially expand the current small local product. + +## Launch implications + +Keep the article's publication-after-review boundary. Modern memory systems can update state, share structured blocks, and validate evidence. Present TaskSeam's combination and workflow as its focus without claiming other systems cannot represent authority. + +The strongest next launch asset would be a reproducible recording: accept a decision in one host, replace it in another, open a fresh chat in the first, and recover correct current state with evidence. Pair it with measured limitations and a reproducible evaluation report. diff --git a/plugins/taskseam/.codex-plugin/plugin.json b/plugins/taskseam/.codex-plugin/plugin.json index 323a5ce..da7449d 100644 --- a/plugins/taskseam/.codex-plugin/plugin.json +++ b/plugins/taskseam/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "taskseam", - "version": "0.1.0", + "version": "0.2.0", "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 9ac464f..df72b1c 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.1.1", + "version": "0.2.0", "description": "Continue versioned task state across AI agents with local evidence and per-agent deltas.", "author": { "name": "Sai Sandeep Kantareddy", diff --git a/plugins/taskseam/skills/task-continuity/SKILL.md b/plugins/taskseam/skills/task-continuity/SKILL.md index 8bdfacc..e4043ca 100644 --- a/plugins/taskseam/skills/task-continuity/SKILL.md +++ b/plugins/taskseam/skills/task-continuity/SKILL.md @@ -9,10 +9,12 @@ Use TaskSeam as the project task-state layer when its MCP tools are available. ## Start or resume work -1. Call `taskseam_continue` once with a stable lowercase target identifying this agent, such as `codex` or `claude-code`. -2. Treat returned current items and changes as task evidence. Do not invent missing context. -3. If there are no unseen changes, continue without making TaskSeam the focus of the response. -4. Call `taskseam_explain` when the origin or reasoning for an item matters. +1. If the session already starts with a "TaskSeam:" state brief (injected by the session-start hook), use it as current state. Still call `taskseam_continue` once so later changes arrive as a delta. +2. Otherwise call `taskseam_continue` once with a stable lowercase target identifying this agent, such as `codex` or `claude-code`. + Pass `full: true` in a fresh chat or after losing context, because an unchanged delta does not mean the task is empty. +3. Treat returned current items and changes as task evidence. Do not invent missing context. +4. If there are no unseen changes, continue without making TaskSeam the focus of the response. +5. Call `taskseam_explain` when the origin or reasoning for an item matters. ## Save durable state @@ -28,6 +30,8 @@ Do not record brainstorming, recommendations awaiting acceptance, implementation Use `taskseam_resolve` when the user explicitly answers a stored open question. Include `supersedes` when that answer also replaces an earlier decision. +Use `taskseam_retire` with a short `reason` when the user says a stored item no longer applies and nothing replaces it. Item IDs accept unique prefixes of at least four characters. + ## Interaction behavior - Use the host's normal approval UI for write tools. diff --git a/pyproject.toml b/pyproject.toml index 5b8f6e7..0c08c42 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "taskseam" -version = "0.1.1" +version = "0.2.0" description = "Local-first task continuity across AI coding agents" readme = "README.md" requires-python = ">=3.9" diff --git a/taskseam/__init__.py b/taskseam/__init__.py index 1c3de52..4729a52 100644 --- a/taskseam/__init__.py +++ b/taskseam/__init__.py @@ -1,3 +1,3 @@ """Local task state and handoff tools.""" -__version__ = "0.1.1" +__version__ = "0.2.0" diff --git a/taskseam/__main__.py b/taskseam/__main__.py index 5083c91..cceebdc 100644 --- a/taskseam/__main__.py +++ b/taskseam/__main__.py @@ -68,6 +68,8 @@ def parser(): setup.add_argument("tool", nargs="?", choices=("codex", "claude-code"), help="Configure one tool; omit to configure every detected tool") setup.add_argument("--dry-run", action="store_true") + setup.add_argument("--no-hooks", action="store_true", + help="Skip the session-start hook that loads project state automatically") commands.add_parser("prompt", help="Print the prompt for creating an import packet") import_command = commands.add_parser("import", help="Preview or apply a TaskSeam state packet") import_command.add_argument("path", nargs="?", help="JSON file; omit to read standard input") @@ -84,12 +86,52 @@ def parser(): handoff = commands.add_parser("handoff", help="Deliver changes since a target's last handoff") handoff.add_argument("--to", required=True, dest="target") handoff.add_argument("--task-id", help="Defaults to the active workspace task") + handoff.add_argument("--full", action="store_true", + help="Also include current state for a fresh chat or lost context") + show = commands.add_parser("show", help="Print the active task's state in readable form") + show.add_argument("task_id", nargs="?", help="Defaults to the active workspace task") + drop = commands.add_parser("drop", help="Retire an item that no longer applies") + drop.add_argument("item_id", help="Item ID or unique prefix") + drop.add_argument("--reason", required=True) + drop.add_argument("--source", default="manual") + export = commands.add_parser("export", help="Write deterministic JSON or Markdown state") + export.add_argument("--format", choices=("json", "markdown"), default="json") + export.add_argument("--history", action="store_true", + help="Include superseded, resolved, and retired items (JSON only)") + destination = export.add_mutually_exclusive_group() + destination.add_argument("--output", "-o", help="Write to a file instead of standard output") + 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") + 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)") + hook_install = hook_sub.add_parser("install", help="Install the SessionStart hook") + hook_install.add_argument("tool", nargs="?", choices=("codex", "claude-code")) + hook_install.add_argument("--dry-run", action="store_true") return p +def _task_or_active(task_id, workspace): + task_id = task_id or (active_task(workspace) if workspace else None) + if not task_id: + raise ValueError("Provide a task ID or run this command in a TaskSeam workspace") + return task_id + + +def _agents_md_block(task, items): + from .render import brief + body = brief(task, items, header=False) + body = "\n".join("#" + line if line.startswith("## ") else line for line in body.splitlines()) + return "## Project state (TaskSeam: {})\n\n{}\n".format(task["title"], body) + + def main(argv=None): args = parser().parse_args(argv) try: + if args.command == "hook" and args.action == "session-start": + from .hooks import session_start + return session_start() if args.command == "init": title = args.title or Path.cwd().name @@ -129,6 +171,10 @@ def create_task(path, task_title): result = setup_claude(sys.executable, args.dry_run) else: result = setup_detected(sys.executable, args.dry_run) + if not args.no_hooks: + from .hooks import install_detected + 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)) return 0 if args.command == "import": @@ -164,6 +210,11 @@ def create_task(path, task_title): from .mcp import run run(args.db, task_id=active_task(workspace) if workspace else None) return 0 + if args.command == "hook": + from .hooks import install_detected + tools = [args.tool] if args.tool else None + print(json.dumps(install_detected(sys.executable, args.dry_run, tools), indent=2)) + return 0 if args.command == "version": from . import __version__ print(__version__) @@ -180,29 +231,66 @@ def create_task(path, task_title): elif args.command == "event": result = {"event_id": store.add_event(args.task_id, args.source, args.body)} elif args.command == "item": + supersedes = args.supersedes and store.resolve_item_id(args.supersedes, args.task_id) result = {"item_id": store.add_item(args.task_id, args.kind, args.body, - args.source, args.supersedes)} - elif args.command == "record": - if not workspace: - raise ValueError("No TaskSeam workspace found; run 'taskseam init'") - result = {"item_id": store.add_item(active_task(workspace), args.kind, args.body, - args.source, args.supersedes)} - elif args.command == "resolve": - if not workspace: - raise ValueError("No TaskSeam workspace found; run 'taskseam init'") - result = {"item_id": store.resolve_question(active_task(workspace), args.question_id, - args.decision, args.source, args.supersedes), - "resolved_question": args.question_id} - elif args.command == "supersede": + args.source, supersedes)} + elif args.command in ("record", "resolve", "supersede", "drop"): if not workspace: raise ValueError("No TaskSeam workspace found; run 'taskseam init'") - store.set_supersession(active_task(workspace), args.old_item_id, args.new_item_id) - result = {"superseded": args.old_item_id, "replacement": args.new_item_id} + task_id = active_task(workspace) + + def ref(value): + return store.resolve_item_id(value, task_id) if value else None + + if args.command == "record": + result = {"item_id": store.add_item(task_id, args.kind, args.body, + args.source, ref(args.supersedes))} + elif args.command == "resolve": + question_id = ref(args.question_id) + result = {"item_id": store.resolve_question(task_id, question_id, args.decision, + args.source, ref(args.supersedes)), + "resolved_question": question_id} + elif args.command == "supersede": + old, new = ref(args.old_item_id), ref(args.new_item_id) + store.set_supersession(task_id, old, new) + result = {"superseded": old, "replacement": new} + else: + result = store.retire_item(task_id, ref(args.item_id), args.reason, args.source) + elif args.command == "show": + from .render import brief + context = store.context(_task_or_active(args.task_id, workspace)) + print(brief(context["task"], context["items"]), end="") + return 0 + elif args.command == "export": + from .render import brief, splice_agents_md + task_id = _task_or_active(args.task_id, workspace) + if args.history and args.format != "json": + raise ValueError("--history is only available with --format json") + if args.agents_md: + context = store.context(task_id) + target = Path(args.agents_md) + existing = target.read_text(encoding="utf-8") if target.exists() else "" + target.write_text(splice_agents_md( + existing, _agents_md_block(context["task"], context["items"])), encoding="utf-8") + print("taskseam: updated {}. It is usually committed to Git; review the block " + "before sharing.".format(target), file=sys.stderr) + return 0 + if args.format == "json": + text = json.dumps(store.export(task_id, history=args.history), indent=2, + sort_keys=True) + "\n" + else: + snapshot = store.export(task_id) + text = brief(snapshot["task"], snapshot["items"]) + if args.output: + Path(args.output).write_text(text, encoding="utf-8") + else: + sys.stdout.write(text) + return 0 elif args.command == "handoff": task_id = args.task_id or (active_task(workspace) if workspace else None) if not task_id: raise ValueError("Provide a task ID or run this command in a TaskSeam workspace") - result = store.handoff(task_id, args.target) + result = store.handoff(task_id, args.target, full=args.full) elif args.command == "checkpoint": task_id = args.task_id or (active_task(workspace) if workspace else None) if not task_id: @@ -216,7 +304,7 @@ def create_task(path, task_title): raise ValueError("Provide a task ID or run this command in a TaskSeam workspace") result = store.context(task_id) else: - result = store.explain(args.item_id) + result = store.explain(store.resolve_item_id(args.item_id)) print(json.dumps(result, indent=2)) return 0 finally: diff --git a/taskseam/hooks.py b/taskseam/hooks.py new file mode 100644 index 0000000..e74311a --- /dev/null +++ b/taskseam/hooks.py @@ -0,0 +1,145 @@ +"""Session-start hooks that load TaskSeam state without relying on a tool call. + +Claude Code and Codex both run SessionStart hooks and add their plain stdout to +the model's context. TaskSeam uses that to put current project state into every +new, cleared, compacted, or resumed session. The hook is read-only: it does not +advance any agent's delivery position, so ``taskseam_continue`` deltas still work. +""" + +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +from .render import brief +from .store import Store +from .workspace import active_task, database_path, find_workspace + +HOOK_MARKER = "taskseam hook session-start" +MATCHER = "startup|resume|clear|compact" +# Claude Code caps hook context at 10,000 characters; Codex defaults to about +# 2,500 tokens. Stay below both so the brief is never truncated by the host. +BUDGET = 6000 +GUIDANCE = ("TaskSeam is connected for this project. When the user explicitly accepts a decision, " + "sets a constraint, or leaves a material question open, save it with taskseam_record " + "(or taskseam_resolve / taskseam_retire); call taskseam_continue for changes made by " + "other agents during this session.") + + +def session_start(stdin=None, stdout=None): + """Print the active task's brief; stay silent outside a TaskSeam workspace.""" + stdin = stdin or sys.stdin + stdout = stdout or sys.stdout + payload = {} + try: + if not stdin.isatty(): + raw = stdin.read() + payload = json.loads(raw) if raw.strip() else {} + except (ValueError, OSError): + payload = {} + cwd = payload.get("cwd") if isinstance(payload, dict) else None + try: + workspace = find_workspace(cwd or os.getcwd()) + if not workspace: + return 0 + store = Store(database_path(workspace)) + try: + context = store.context(active_task(workspace)) + finally: + store.close() + except Exception as exc: # A hook must never block the user's session. + print("taskseam hook: " + str(exc), file=sys.stderr) + return 0 + stdout.write(brief(context["task"], context["items"], budget=BUDGET)) + stdout.write("\n" + GUIDANCE + "\n") + stdout.flush() + return 0 + + +def hook_command(python_executable=None): + python = python_executable or sys.executable + args = [python, "-m", "taskseam", "hook", "session-start"] + if os.name == "nt": + return subprocess.list2cmdline(args) + import shlex + return " ".join(shlex.quote(arg) for arg in args) + + +def claude_settings_path(): + return Path.home() / ".claude" / "settings.json" + + +def codex_hooks_path(): + return Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex") / "hooks.json" + + +def install(path, python_executable=None, dry_run=False): + """Add or refresh the TaskSeam SessionStart hook in a hooks JSON file. + + Claude Code's settings.json and Codex's hooks.json share this structure. + Unrelated settings and hooks are preserved; an existing TaskSeam entry is + updated in place so reinstalling never duplicates it. + """ + path = Path(path) + command = hook_command(python_executable) + original = path.read_text(encoding="utf-8") if path.exists() else "" + try: + data = json.loads(original) if original.strip() else {} + except json.JSONDecodeError as exc: + raise ValueError("Cannot update {}: invalid JSON ({})".format(path, exc)) from exc + if not isinstance(data, dict): + raise ValueError("Cannot update {}: expected a JSON object".format(path)) + hooks = data.setdefault("hooks", {}) + if not isinstance(hooks, dict): + raise ValueError("Cannot update {}: 'hooks' must be an object".format(path)) + groups = hooks.setdefault("SessionStart", []) + if not isinstance(groups, list): + raise ValueError("Cannot update {}: 'hooks.SessionStart' must be a list".format(path)) + entry = {"type": "command", "command": command, "timeout": 10} + status = "installed" + for group in groups: + for handler in (group.get("hooks") or []) if isinstance(group, dict) else []: + if isinstance(handler, dict) and HOOK_MARKER in str(handler.get("command", "")): + status = "unchanged" if handler.get("command") == command else "updated" + handler["command"] = command + break + else: + continue + break + else: + groups.append({"matcher": MATCHER, "hooks": [entry]}) + result = {"path": str(path), "status": status, "command": command} + if dry_run or status == "unchanged": + result["written"] = False + return result + path.parent.mkdir(parents=True, exist_ok=True) + if original: + backup = path.with_name(path.name + ".taskseam-backup") + if not backup.exists(): + backup.write_text(original, encoding="utf-8") + result["backup"] = str(backup) + temporary = path.with_name(path.name + ".taskseam-tmp") + temporary.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + os.replace(str(temporary), str(path)) + result["written"] = True + return result + + +def install_detected(python_executable=None, dry_run=False, tools=None): + """Install the hook for each supported agent found on PATH.""" + targets = (("claude-code", "claude", claude_settings_path), + ("codex", "codex", codex_hooks_path)) + installed, skipped = [], [] + 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"}) + continue + result = install(locate(), python_executable, dry_run) + if name == "codex": + result["note"] = "Codex runs new hooks only after you review and trust them with /hooks" + installed.append({"tool": name, **result}) + return {"hooks": installed, "skipped": skipped} diff --git a/taskseam/mcp.py b/taskseam/mcp.py index 5cbd5ee..35814e4 100644 --- a/taskseam/mcp.py +++ b/taskseam/mcp.py @@ -4,16 +4,25 @@ import sys from . import __version__ +from .render import brief from .store import Store +# Handshake-based revisions this server implements. The newest is preferred; +# an older client receives the revision it requested. +PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26") +RESOURCE_URI = "taskseam://active/brief" + SERVER_INSTRUCTIONS = """Use TaskSeam for continuity when an active workspace task is available. At the start of relevant project work, call taskseam_continue once with a stable lowercase target -for this agent. Use the returned state as evidence and do not invent missing context. During normal +for this agent. Set full=true in a fresh chat or after losing prior context; otherwise use the delta. +An unchanged delta does not mean the task has no current state. +Use the returned state as evidence and do not invent missing context. During normal work, call taskseam_record only for a decision the user explicitly accepts, an active constraint, or a material unresolved question. Never store brainstorming, unaccepted recommendations, secrets, or unrelated personal context. Use taskseam_resolve when the user explicitly answers a stored -question. Keep durable items concise and self-contained, preserve supersession links, and use the +question. Use taskseam_retire when the user says a stored item no longer applies and nothing +replaces it. Item IDs accept unique prefixes of at least four characters. Keep durable items concise and self-contained, preserve supersession links, and use the host's normal approval flow for writes. Do not ask the user to run TaskSeam CLI record commands when an MCP write tool can complete the operation.""" @@ -33,10 +42,12 @@ "inputSchema": {"type": "object", "properties": {"item_id": {"type": "string"}}, "required": ["item_id"]}, "annotations": {"readOnlyHint": True}}, {"name": "taskseam_continue", - "description": "Return changes since a target last received this task, then mark them delivered", + "description": "Return changes since a target last received this task, then mark them delivered. Set full=true to also recover current state in a fresh chat.", "inputSchema": {"type": "object", "properties": { "task_id": {"type": "string", "description": "Omit for the active workspace task"}, - "target": {"type": "string", "description": "Receiving tool, such as codex"}}, + "target": {"type": "string", "description": "Receiving tool, such as codex"}, + "full": {"type": "boolean", "default": False, + "description": "Include current state even if this target has no unseen changes"}}, "required": ["target"]}}, {"name": "taskseam_record", "description": "Record one user-accepted decision, active constraint, or unresolved question", @@ -58,6 +69,21 @@ "supersedes": {"type": "string", "description": "Earlier decision replaced by this resolution"}}, "required": ["question_id", "decision", "source"]}, "annotations": {"readOnlyHint": False}}, + {"name": "taskseam_retire", + "description": "Remove a decision, constraint, or question the user says no longer applies, when nothing replaces it", + "inputSchema": {"type": "object", "properties": { + "task_id": {"type": "string", "description": "Omit for the active workspace task"}, + "item_id": {"type": "string", "description": "Item ID or unique prefix"}, + "reason": {"type": "string", "description": "Why the item no longer applies"}, + "source": {"type": "string", "description": "Originating agent or user"}}, + "required": ["item_id", "reason", "source"]}, + "annotations": {"readOnlyHint": False, "destructiveHint": False}}, +] + +PROMPTS = [ + {"name": "continue", + "title": "Continue with TaskSeam", + "description": "Load this project's accepted decisions, constraints, and open questions"}, ] @@ -72,9 +98,11 @@ def _error(request_id, code, message): def handle(store, request, active_task_id=None): request_id, method = request.get("id"), request.get("method") if method == "initialize": + requested = (request.get("params") or {}).get("protocolVersion") return _result(request_id, { - "protocolVersion": "2025-06-18", - "capabilities": {"tools": {"listChanged": False}}, + "protocolVersion": requested if requested in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0], + "capabilities": {"tools": {"listChanged": False}, "prompts": {"listChanged": False}, + "resources": {"listChanged": False}}, "serverInfo": {"name": "taskseam", "version": __version__}, "instructions": SERVER_INSTRUCTIONS, }) @@ -82,8 +110,11 @@ def handle(store, request, active_task_id=None): return _result(request_id, {}) if method == "tools/list": return _result(request_id, {"tools": TOOLS}) - if method == "notifications/initialized": + if isinstance(method, str) and method.startswith("notifications/"): return None + if method in ("prompts/list", "prompts/get", "resources/list", "resources/read"): + return _prompt_or_resource(store, request_id, method, request.get("params") or {}, + active_task_id) if method != "tools/call": return _error(request_id, -32601, "Method not found") params = request.get("params") or {} @@ -96,33 +127,78 @@ def handle(store, request, active_task_id=None): elif name == "taskseam_delta": value = store.delta(args["base"], args["head"]) elif name == "taskseam_explain": - value = store.explain(args["item_id"]) + value = store.explain(store.resolve_item_id(args["item_id"])) elif name == "taskseam_continue": task_id = args.get("task_id") or active_task_id if not task_id: raise ValueError("task_id is required outside an initialized workspace") - value = store.handoff(task_id, args["target"]) + value = store.handoff(task_id, args["target"], full=args.get("full", False)) elif name == "taskseam_record": task_id = args.get("task_id") or active_task_id if not task_id: raise ValueError("task_id is required outside an initialized workspace") + supersedes = args.get("supersedes") item_id = store.add_item(task_id, args["kind"], args["body"], args["source"], - args.get("supersedes")) + store.resolve_item_id(supersedes, task_id) if supersedes else None) value = {"item_id": item_id, "recorded": True} elif name == "taskseam_resolve": task_id = args.get("task_id") or active_task_id if not task_id: raise ValueError("task_id is required outside an initialized workspace") - item_id = store.resolve_question(task_id, args["question_id"], args["decision"], - args["source"], args.get("supersedes")) - value = {"item_id": item_id, "resolved_question": args["question_id"]} + supersedes = args.get("supersedes") + question_id = store.resolve_item_id(args["question_id"], task_id) + item_id = store.resolve_question(task_id, question_id, args["decision"], args["source"], + store.resolve_item_id(supersedes, task_id) if supersedes else None) + value = {"item_id": item_id, "resolved_question": question_id} + elif name == "taskseam_retire": + task_id = args.get("task_id") or active_task_id + if not task_id: + raise ValueError("task_id is required outside an initialized workspace") + value = store.retire_item(task_id, store.resolve_item_id(args["item_id"], task_id), + args["reason"], args["source"]) else: return _error(request_id, -32602, "Unknown tool: " + str(name)) - return _result(request_id, {"content": [{"type": "text", "text": json.dumps(value, indent=2)}]}) + result = {"content": [{"type": "text", "text": json.dumps(value, indent=2)}]} + result["structuredContent"] = value if isinstance(value, dict) else {"result": value} + return _result(request_id, result) except (KeyError, ValueError) as exc: return _result(request_id, {"content": [{"type": "text", "text": str(exc)}], "isError": True}) +def _prompt_or_resource(store, request_id, method, params, active_task_id): + if method == "prompts/list": + return _result(request_id, {"prompts": PROMPTS}) + if method == "resources/list": + resources = [] + if active_task_id: + resources.append({"uri": RESOURCE_URI, "name": "active-task-brief", + "title": "TaskSeam project state", "mimeType": "text/markdown", + "description": "Current decisions, constraints, and open questions"}) + return _result(request_id, {"resources": resources}) + if method == "prompts/get" and params.get("name") != "continue": + return _error(request_id, -32602, "Unknown prompt: " + str(params.get("name"))) + if method == "resources/read" and params.get("uri") != RESOURCE_URI: + return _error(request_id, -32002, "Resource not found: " + str(params.get("uri"))) + if not active_task_id: + return _error(request_id, -32002, "No active TaskSeam workspace; run 'taskseam init'") + try: + context = store.context(active_task_id) + except ValueError as exc: + return _error(request_id, -32002, str(exc)) + text = brief(context["task"], context["items"]) + if method == "resources/read": + return _result(request_id, {"contents": [ + {"uri": RESOURCE_URI, "mimeType": "text/markdown", "text": text}]}) + return _result(request_id, { + "description": "TaskSeam state for " + context["task"]["title"], + "messages": [{"role": "user", "content": {"type": "text", "text": ( + "Continue this project using its recorded TaskSeam state below. Summarize the accepted " + "decisions, active constraints, and open questions that matter for the next step, then " + "call taskseam_continue once so later changes from other agents arrive as a delta.\n\n" + + text)}}], + }) + + def run(db_path, input_stream=None, output_stream=None, task_id=None): input_stream = input_stream or sys.stdin output_stream = output_stream or sys.stdout diff --git a/taskseam/render.py b/taskseam/render.py new file mode 100644 index 0000000..d4706f0 --- /dev/null +++ b/taskseam/render.py @@ -0,0 +1,78 @@ +"""Human-readable renderings of TaskSeam state.""" + +SHORT_ID = 7 +SECTIONS = ( + ("decision", "Accepted decisions"), + ("constraint", "Active constraints"), + ("question", "Open questions"), +) +AGENTS_MD_START = "" +AGENTS_MD_END = "" + + +def short(item_id): + return item_id[:SHORT_ID] + + +def _line(item): + body = " ".join(item["body"].split()) + return "- {} `{}` _({})_".format(body, short(item["id"]), item.get("source") or "unknown") + + +def brief(task, items, budget=None, header=True, ids=True): + """Render current state as Markdown. + + ``budget`` caps the output in characters. Items that do not fit are never + dropped silently: the brief ends with an explicit omission count per kind. + """ + lines = [] + if header: + lines.append("# TaskSeam: " + task["title"]) + lines.append("") + if not items: + lines.append("No accepted decisions, constraints, or open questions are recorded yet.") + return "\n".join(lines) + "\n" + footer = ("Recorded project state with its source in parentheses; check it against the code " + "before relying on it. IDs accept unique prefixes; `taskseam explain ` shows evidence.") + omitted = {} + used = sum(len(line) + 1 for line in lines) + len(footer) + 200 + for kind, title in SECTIONS: + group = [item for item in items if item["kind"] == kind] + if not group: + continue + section = ["## {} ({})".format(title, len(group))] + for item in group: + text = _line(item) if ids else "- " + " ".join(item["body"].split()) + cost = len(text) + 1 + (len(section[0]) + 2 if len(section) == 1 else 0) + if budget is not None and used + cost > budget: + omitted[kind] = omitted.get(kind, 0) + 1 + continue + used += cost + section.append(text) + if len(section) > 1: + lines.extend(section) + lines.append("") + if omitted: + parts = ["{} {}{}".format(count, kind, "s" if count != 1 else "") + for kind, count in omitted.items()] + lines.append("**Omitted to fit the size budget:** " + ", ".join(parts) + + ". Call the `taskseam_context` tool or run `taskseam show` for everything.") + lines.append("") + if ids: + lines.append("_" + footer + "_") + return "\n".join(lines).rstrip() + "\n" + + +def splice_agents_md(existing, block): + """Insert or replace the TaskSeam-managed block inside an AGENTS.md-style file.""" + managed = "{}\n\n{}{}\n".format( + AGENTS_MD_START, block if block.endswith("\n") else block + "\n", AGENTS_MD_END) + start, end = existing.find(AGENTS_MD_START), existing.find(AGENTS_MD_END) + if start != -1 and end != -1 and end > start: + tail = existing[end + len(AGENTS_MD_END):] + return existing[:start] + managed.rstrip("\n") + tail if tail else existing[:start] + managed + if start != -1 or end != -1: + raise ValueError("Found only one TaskSeam marker; fix the file before exporting") + if not existing: + return managed + return existing.rstrip("\n") + "\n\n" + managed diff --git a/taskseam/store.py b/taskseam/store.py index c5af1ae..27a5c41 100644 --- a/taskseam/store.py +++ b/taskseam/store.py @@ -15,6 +15,10 @@ def _id(): return uuid.uuid4().hex[:12] +SCHEMA_VERSION = 4 +KINDS = ("decision", "constraint", "question") + + class Store: def __init__(self, path): self.path = Path(path).expanduser() @@ -24,7 +28,7 @@ def __init__(self, path): self.db.execute("PRAGMA foreign_keys = ON") self.db.execute("PRAGMA busy_timeout = 5000") schema_version = self.db.execute("PRAGMA user_version").fetchone()[0] - if schema_version > 3: + if schema_version > SCHEMA_VERSION: self.db.close() raise ValueError("Database was created by a newer TaskSeam version") self.db.executescript(""" @@ -57,11 +61,16 @@ def __init__(self, path): delivered_at TEXT NOT NULL, PRIMARY KEY (task_id, target) ); + CREATE TABLE IF NOT EXISTS retirements ( + item_id TEXT PRIMARY KEY REFERENCES items(id), + event_id TEXT NOT NULL REFERENCES events(id), + created_at TEXT NOT NULL + ); CREATE INDEX IF NOT EXISTS events_task_idx ON events(task_id); CREATE INDEX IF NOT EXISTS items_task_idx ON items(task_id); CREATE INDEX IF NOT EXISTS checkpoints_task_idx ON checkpoints(task_id); - PRAGMA user_version = 3; """) + self.db.execute("PRAGMA user_version = %d" % SCHEMA_VERSION) self.db.commit() def close(self): @@ -106,6 +115,8 @@ def add_item(self, task_id, kind, body, source, supersedes=None): raise ValueError("Superseded item must exist in the same task and have the same kind") if self.db.execute("SELECT 1 FROM items WHERE supersedes = ?", (supersedes,)).fetchone(): raise ValueError("Item has already been superseded") + if self._is_retired(supersedes): + raise ValueError("Item has been retired and cannot be superseded") event_id, item_id = _id(), _id() with self.db: self.db.execute("INSERT INTO events VALUES (?, ?, ?, ?, ?)", @@ -145,7 +156,8 @@ def items(self, task_id): self.task(task_id) rows = self.db.execute(""" SELECT i.*, e.source, - (SELECT r.question_id FROM resolutions r WHERE r.resolution_item_id = i.id) AS resolves + (SELECT r.question_id FROM resolutions r WHERE r.resolution_item_id = i.id) AS resolves, + (SELECT t.created_at FROM retirements t WHERE t.item_id = i.id) AS retired_at FROM items i JOIN events e ON e.id = i.event_id WHERE i.task_id = ? ORDER BY i.created_at, i.rowid """, (task_id,)).fetchall() @@ -158,7 +170,71 @@ def current_items(self, task_id): "SELECT question_id FROM resolutions WHERE question_id IN " "(SELECT id FROM items WHERE task_id = ?)", (task_id,) )} - return [row for row in rows if row["id"] not in replaced and row["id"] not in resolved] + current = [row for row in rows if row["id"] not in replaced and row["id"] not in resolved + and row["retired_at"] is None] + for row in current: + del row["retired_at"] + return current + + def _is_retired(self, item_id): + return self.db.execute("SELECT 1 FROM retirements WHERE item_id = ?", (item_id,)).fetchone() is not None + + def resolve_item_id(self, reference, task_id=None): + """Expand a unique item ID prefix (at least four characters) to a full ID.""" + if not isinstance(reference, str) or len(reference.strip()) < 4: + raise ValueError("Item references need at least four characters") + reference = reference.strip().lower() + query, params = "SELECT id FROM items WHERE id LIKE ? ESCAPE '\\'", [ + reference.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"] + if task_id: + query += " AND task_id = ?" + params.append(task_id) + matches = [row[0] for row in self.db.execute(query, params).fetchall()] + if reference in matches: + return reference + if not matches: + raise ValueError("Unknown item: " + reference) + if len(matches) > 1: + raise ValueError("Ambiguous item reference {}: matches {}".format( + reference, ", ".join(sorted(matches)))) + return matches[0] + + def retire_item(self, task_id, item_id, reason, source): + """Remove a current item from task state without replacing it. + + The item and its evidence remain in history; the retirement is its own event. + """ + self.task(task_id) + if not isinstance(reason, str) or not reason.strip(): + raise ValueError("Retiring an item requires a reason") + if item_id not in {row["id"] for row in self.current_items(task_id)}: + row = self.db.execute("SELECT task_id FROM items WHERE id = ?", (item_id,)).fetchone() + if row is None or row["task_id"] != task_id: + raise ValueError("Item must exist in the active task") + raise ValueError("Only current items can be retired; this item is already superseded, " + "resolved, or retired") + event_id, created = _id(), _now() + with self.db: + self.db.execute("INSERT INTO events VALUES (?, ?, ?, ?, ?)", + (event_id, task_id, source, "Retired " + item_id + ": " + reason.strip(), + created)) + self.db.execute("INSERT INTO retirements VALUES (?, ?, ?)", (item_id, event_id, created)) + return {"retired": item_id, "event_id": event_id} + + def export(self, task_id, history=False): + """Return a deterministic, schema-versioned snapshot of a task.""" + task = self.task(task_id) + fields = ("id", "kind", "body", "source", "created_at", "supersedes", "resolves") + rows = self.items(task_id) if history else self.current_items(task_id) + items = [] + for row in rows: + item = {key: row[key] for key in fields} + if history: + item["retired_at"] = row["retired_at"] + items.append(item) + items.sort(key=lambda item: (KINDS.index(item["kind"]), item["created_at"], item["id"])) + return {"taskseam_export": 1, "history": history, + "task": {"id": task["id"], "title": task["title"]}, "items": items} def resolve_question(self, task_id, question_id, decision, source, supersedes=None): self.task(task_id) @@ -214,6 +290,8 @@ def set_supersession(self, task_id, old_item_id, new_item_id): "SELECT 1 FROM items WHERE supersedes = ? AND id != ?", (old_item_id, new_item_id) ).fetchone(): raise ValueError("Old item has already been superseded") + if self._is_retired(old_item_id) or self._is_retired(new_item_id): + raise ValueError("Retired items cannot be linked by supersession") with self.db: self.db.execute("UPDATE items SET supersedes = ? WHERE id = ?", (old_item_id, new_item_id)) @@ -264,8 +342,11 @@ def delta(self, base_id, head_id): "removed": [by_id[item_id] for item_id in json.loads(base["snapshot"]) if item_id not in after], } - def handoff(self, task_id, target): + def handoff(self, task_id, target, full=False): + """Deliver a delta, optionally including current state for a fresh session.""" self.task(task_id) + if not isinstance(full, bool): + raise ValueError("full must be a boolean") if not isinstance(target, str) or not target.strip(): raise ValueError("Handoff target cannot be empty") target = target.strip().lower() @@ -279,8 +360,11 @@ def handoff(self, task_id, target): if base_id: previous = self._checkpoint(base_id) if json.loads(previous["snapshot"]) == current_ids: - return {"task": self.task(task_id), "target": target, "base": base_id, - "head": base_id, "added": [], "removed": [], "changed": False} + result = {"task": self.task(task_id), "target": target, "base": base_id, + "head": base_id, "added": [], "removed": [], "changed": False} + if full: + result["current"] = current + return result head_id = self.checkpoint(task_id) if base_id: result = self.delta(base_id, head_id) @@ -296,4 +380,6 @@ def handoff(self, task_id, target): delivered_at = excluded.delivered_at """, (task_id, target, head_id, _now())) result.update({"target": target, "changed": bool(result["added"] or result["removed"])}) + if full: + result["current"] = current return result diff --git a/tests/test_cli.py b/tests/test_cli.py index b38770a..b95e813 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -28,6 +28,10 @@ def run(*args): self.assertEqual(delta["removed"][0]["id"], first) self.assertEqual(run("context", task)["items"][0]["body"], "Use SQLite") self.assertEqual(run("explain", second)["source"], "claude") + run("handoff", "--task-id", task, "--to", "codex") + recovered = run("handoff", "--task-id", task, "--to", "codex", "--full") + self.assertFalse(recovered["changed"]) + self.assertEqual([i["id"] for i in recovered["current"]], [second]) if __name__ == "__main__": diff --git a/tests/test_continuity_features.py b/tests/test_continuity_features.py new file mode 100644 index 0000000..4766f28 --- /dev/null +++ b/tests/test_continuity_features.py @@ -0,0 +1,248 @@ +import io +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from taskseam import hooks +from taskseam.mcp import PROTOCOL_VERSIONS, handle +from taskseam.render import AGENTS_MD_END, AGENTS_MD_START, brief, splice_agents_md +from taskseam.store import Store + +ROOT = Path(__file__).resolve().parents[1] + + +class RetireAndReferenceTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.store = Store(Path(self.tmp.name) / "state.db") + self.task = self.store.create_task("Retire") + + def tearDown(self): + self.store.close() + self.tmp.cleanup() + + def test_retired_item_leaves_state_and_appears_as_removed_in_delta(self): + item = self.store.add_item(self.task, "constraint", "Must work offline", "user") + self.store.handoff(self.task, "codex") + result = self.store.retire_item(self.task, item, "Offline was cut", "user") + self.assertEqual(result["retired"], item) + self.assertEqual(self.store.current_items(self.task), []) + delta = self.store.handoff(self.task, "codex") + self.assertEqual([i["id"] for i in delta["removed"]], [item]) + self.assertIn("Offline was cut", self.store.events(self.task)[-1]["body"]) + + def test_retire_rejects_non_current_items_and_empty_reasons(self): + old = self.store.add_item(self.task, "decision", "Use Markdown", "user") + self.store.add_item(self.task, "decision", "Use SQLite", "user", old) + with self.assertRaisesRegex(ValueError, "Only current items"): + self.store.retire_item(self.task, old, "stale", "user") + current = self.store.current_items(self.task)[0]["id"] + with self.assertRaisesRegex(ValueError, "reason"): + self.store.retire_item(self.task, current, " ", "user") + self.store.retire_item(self.task, current, "Dropped storage work", "user") + with self.assertRaises(ValueError): + self.store.add_item(self.task, "decision", "Use JSON", "user", current) + other = self.store.create_task("Other") + foreign = self.store.add_item(other, "decision", "Elsewhere", "user") + with self.assertRaisesRegex(ValueError, "active task"): + self.store.retire_item(self.task, foreign, "wrong task", "user") + + def test_prefix_references_resolve_uniquely(self): + item = self.store.add_item(self.task, "decision", "Use SQLite", "user") + self.assertEqual(self.store.resolve_item_id(item[:5].upper(), self.task), item) + self.assertEqual(self.store.resolve_item_id(item, self.task), item) + with self.assertRaisesRegex(ValueError, "four"): + self.store.resolve_item_id(item[:3]) + with self.assertRaisesRegex(ValueError, "Unknown"): + self.store.resolve_item_id("%%%%") + self.store.db.execute("UPDATE items SET id = 'abcd11111111' WHERE id = ?", (item,)) + self.store.add_item(self.task, "decision", "Second", "user") + self.store.db.execute("UPDATE items SET id = 'abcd22222222' WHERE body = 'Second'") + with self.assertRaisesRegex(ValueError, "Ambiguous"): + self.store.resolve_item_id("abcd", self.task) + + def test_export_is_deterministic_and_history_is_opt_in(self): + old = self.store.add_item(self.task, "decision", "Use Markdown", "user") + self.store.add_item(self.task, "question", "Offline?", "user") + self.store.add_item(self.task, "constraint", "Local only", "user") + self.store.add_item(self.task, "decision", "Use SQLite", "user", old) + first = self.store.export(self.task) + self.assertEqual(first, self.store.export(self.task)) + self.assertEqual([i["kind"] for i in first["items"]], ["decision", "constraint", "question"]) + self.assertEqual(first["taskseam_export"], 1) + self.assertNotIn("retired_at", first["items"][0]) + history = self.store.export(self.task, history=True) + self.assertEqual(len(history["items"]), 4) + + +class RenderTests(unittest.TestCase): + def items(self, count, kind="decision"): + return [{"id": "{:012x}".format(n), "kind": kind, "body": "Decision number %d" % n, + "source": "user"} for n in range(count)] + + def test_budget_reports_omissions_instead_of_dropping_silently(self): + task = {"title": "Big"} + text = brief(task, self.items(200), budget=1500) + self.assertLessEqual(len(text), 1600) + self.assertIn("Omitted to fit the size budget", text) + self.assertIn("decisions", text) + self.assertNotIn("Omitted", brief(task, self.items(3), budget=1500)) + + def test_empty_state_is_explicit(self): + self.assertIn("No accepted decisions", brief({"title": "Empty"}, [])) + + def test_agents_md_block_is_inserted_then_replaced(self): + original = "# Agents\n\nRun make test.\n" + once = splice_agents_md(original, "first\n") + self.assertTrue(once.startswith(original.rstrip("\n"))) + twice = splice_agents_md(once + "\n## Footer\n", "second\n") + self.assertIn("second", twice) + self.assertNotIn("first", twice) + self.assertEqual(twice.count(AGENTS_MD_START), 1) + self.assertIn("## Footer", twice) + with self.assertRaises(ValueError): + splice_agents_md(original + AGENTS_MD_END, "x") + + +class HookTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + + def tearDown(self): + self.tmp.cleanup() + + def test_session_start_prints_state_for_hook_cwd(self): + project = self.root / "project" + project.mkdir() + subprocess.run([sys.executable, "-m", "taskseam", "init", "Hooked"], cwd=project, + check=True, capture_output=True, env={**os.environ, "PYTHONPATH": str(ROOT)}) + config = json.loads((project / ".taskseam" / "config.json").read_text()) + store = Store(project / ".taskseam" / "state.db") + store.add_item(config["active_task"], "decision", "Use SQLite", "claude") + store.close() + nested = project / "src" + nested.mkdir() + out = io.StringIO() + code = hooks.session_start(io.StringIO(json.dumps({"cwd": str(nested)})), out) + self.assertEqual(code, 0) + self.assertIn("Use SQLite", out.getvalue()) + self.assertIn("taskseam_record", out.getvalue()) + + def test_session_start_is_silent_outside_workspace_and_with_bad_input(self): + for payload in (json.dumps({"cwd": str(self.root)}), "not json"): + out = io.StringIO() + previous = os.getcwd() + os.chdir(self.root) + try: + self.assertEqual(hooks.session_start(io.StringIO(payload), out), 0) + finally: + os.chdir(previous) + self.assertEqual(out.getvalue(), "") + + def test_install_preserves_settings_and_is_idempotent(self): + path = self.root / "settings.json" + path.write_text(json.dumps({"theme": "dark", "hooks": {"SessionStart": [ + {"matcher": "startup", "hooks": [{"type": "command", "command": "echo hi"}]}]}})) + first = hooks.install(path, "/old/python") + self.assertEqual(first["status"], "installed") + self.assertTrue(Path(first["backup"]).exists()) + self.assertEqual(hooks.install(path, "/old/python")["status"], "unchanged") + self.assertEqual(hooks.install(path, "/new/python")["status"], "updated") + data = json.loads(path.read_text()) + self.assertEqual(data["theme"], "dark") + commands = [h["command"] for g in data["hooks"]["SessionStart"] for h in g["hooks"]] + self.assertEqual(len(commands), 2) + self.assertIn("echo hi", commands) + self.assertTrue(any(c.startswith("/new/python") for c in commands)) + + def test_install_dry_run_and_invalid_json(self): + path = self.root / "hooks.json" + self.assertFalse(hooks.install(path, dry_run=True)["written"]) + self.assertFalse(path.exists()) + path.write_text("{broken") + with self.assertRaisesRegex(ValueError, "invalid JSON"): + hooks.install(path) + self.assertEqual(path.read_text(), "{broken") + + +class McpUpgradeTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.store = Store(Path(self.tmp.name) / "state.db") + self.task = self.store.create_task("MCP") + + def tearDown(self): + self.store.close() + self.tmp.cleanup() + + def call(self, method, params=None, task=True): + return handle(self.store, {"jsonrpc": "2.0", "id": 1, "method": method, "params": params or {}}, + active_task_id=self.task if task else None) + + def test_protocol_negotiation(self): + self.assertEqual(self.call("initialize", {"protocolVersion": "2025-06-18"}) + ["result"]["protocolVersion"], "2025-06-18") + self.assertEqual(self.call("initialize", {"protocolVersion": "1999-01-01"}) + ["result"]["protocolVersion"], PROTOCOL_VERSIONS[0]) + capabilities = self.call("initialize")["result"]["capabilities"] + self.assertIn("prompts", capabilities) + self.assertIn("resources", capabilities) + + def test_retire_tool_accepts_prefix_and_returns_structured_content(self): + item = self.store.add_item(self.task, "constraint", "Offline", "user") + response = self.call("tools/call", {"name": "taskseam_retire", "arguments": { + "item_id": item[:6], "reason": "Cut", "source": "user"}}) + self.assertEqual(response["result"]["structuredContent"]["retired"], item) + self.assertEqual(self.store.current_items(self.task), []) + listed = self.call("tools/call", {"name": "taskseam_list_tasks"}) + self.assertIsInstance(listed["result"]["structuredContent"]["result"], list) + + def test_continue_prompt_and_resource(self): + self.store.add_item(self.task, "decision", "Use SQLite", "claude") + self.assertEqual(self.call("prompts/list")["result"]["prompts"][0]["name"], "continue") + prompt = self.call("prompts/get", {"name": "continue"})["result"] + self.assertIn("Use SQLite", prompt["messages"][0]["content"]["text"]) + uri = self.call("resources/list")["result"]["resources"][0]["uri"] + contents = self.call("resources/read", {"uri": uri})["result"]["contents"] + self.assertIn("Use SQLite", contents[0]["text"]) + self.assertIn("error", self.call("prompts/get", {"name": "nope"})) + self.assertIn("error", self.call("resources/read", {"uri": uri}, task=False)) + self.assertEqual(self.call("resources/list", task=False)["result"]["resources"], []) + self.assertIsNone(self.call("notifications/cancelled")) + + +class CliFeatureTests(unittest.TestCase): + def test_show_drop_and_agents_md_export(self): + with tempfile.TemporaryDirectory() as directory: + env = {**os.environ, "PYTHONPATH": str(ROOT)} + + def run(*args): + return subprocess.run([sys.executable, "-m", "taskseam", *args], cwd=directory, + env=env, capture_output=True, text=True, check=True).stdout + + run("init", "CLI") + item = json.loads(run("record", "constraint", "Offline", "--source", "user"))["item_id"] + run("record", "decision", "Use SQLite", "--source", "claude") + self.assertIn("Offline", run("show")) + run("drop", item[:5], "--reason", "Cut") + shown = run("show") + self.assertNotIn("Offline", shown) + self.assertIn("Use SQLite `", shown) + agents = Path(directory) / "AGENTS.md" + agents.write_text("# Agents\n") + run("export", "--agents-md") + run("export", "--agents-md") + text = agents.read_text() + self.assertEqual(text.count(AGENTS_MD_START), 1) + self.assertIn("Use SQLite", text) + exported = json.loads(run("export")) + self.assertEqual([i["body"] for i in exported["items"]], ["Use SQLite"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 4031efe..b9d5d81 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -44,6 +44,14 @@ def test_continue_uses_active_task_and_tracks_delivery(self): second = handle(self.store, request, active_task_id=task) second_value = json.loads(second["result"]["content"][0]["text"]) self.assertFalse(second_value["changed"]) + request["params"]["arguments"]["full"] = True + recovered = handle(self.store, request, active_task_id=task) + recovered_value = json.loads(recovered["result"]["content"][0]["text"]) + self.assertFalse(recovered_value["changed"]) + self.assertEqual(recovered_value["current"][0]["body"], "Keep data local") + request["params"]["arguments"]["full"] = "false" + invalid = handle(self.store, request, active_task_id=task) + self.assertTrue(invalid["result"]["isError"]) def test_record_and_resolve_use_active_task(self): task = self.store.create_task("Active task") diff --git a/tests/test_store.py b/tests/test_store.py index 990e8d0..e5d36e4 100644 --- a/tests/test_store.py +++ b/tests/test_store.py @@ -89,7 +89,7 @@ def test_version_one_database_migrates(self): legacy.close() migrated = Store(path) try: - self.assertEqual(migrated.db.execute("PRAGMA user_version").fetchone()[0], 3) + self.assertEqual(migrated.db.execute("PRAGMA user_version").fetchone()[0], 4) self.assertIsNotNone(migrated.db.execute( "SELECT name FROM sqlite_master WHERE type='table' AND name='resolutions'" ).fetchone()) @@ -99,6 +99,42 @@ def test_version_one_database_migrates(self): finally: migrated.close() + def test_full_handoff_recovers_state_without_repeating_delta(self): + old = self.store.add_item(self.task, "decision", "Use Markdown", "user") + question = self.store.add_item(self.task, "question", "Offline?", "user") + initial = self.store.handoff(self.task, "codex") + self.store.handoff(self.task, "claude") + new = self.store.add_item(self.task, "decision", "Use SQLite", "user", old) + answer = self.store.resolve_question(self.task, question, "Require offline", "user") + recovered = self.store.handoff(self.task, " CODEX ", full=True) + self.assertEqual({i["id"] for i in recovered["current"]}, {new, answer}) + self.assertEqual({i["id"] for i in recovered["removed"]}, {old, question}) + self.assertEqual(recovered["base"], initial["head"]) + checkpoints = len(self.store.checkpoints(self.task)) + repeated = self.store.handoff(self.task, "codex", full=True) + self.assertFalse(repeated["changed"]) + self.assertEqual(repeated["current"], recovered["current"]) + self.assertEqual(len(self.store.checkpoints(self.task)), checkpoints) + self.assertNotIn("current", self.store.handoff(self.task, "codex")) + other = self.store.handoff(self.task, "claude") + self.assertEqual({i["id"] for i in other["added"]}, {new, answer}) + + def test_full_handoff_empty_and_invalid_requests(self): + empty = self.store.handoff(self.task, "codex", full=True) + self.assertEqual(empty["current"], []) + self.assertFalse(empty["changed"]) + with self.assertRaisesRegex(ValueError, "boolean"): + self.store.handoff(self.task, "claude", full="false") + self.assertIsNone(self.store.handoff(self.task, "claude")["base"]) + + def test_full_handoff_excludes_other_tasks(self): + other = self.store.create_task("Private unrelated task") + self.store.add_item(other, "constraint", "Unrelated material", "user") + item = self.store.add_item(self.task, "constraint", "Local only", "user") + result = self.store.handoff(self.task, "codex", full=True) + self.assertEqual([i["id"] for i in result["current"]], [item]) + self.assertEqual(result["current"][0]["source"], "user") + def test_handoff_tracks_each_target_checkpoint(self): first = self.store.add_item(self.task, "decision", "Use SQLite", "claude") initial = self.store.handoff(self.task, "codex")