taskseam 0.1.1__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. {taskseam-0.1.1 → taskseam-0.2.0}/PKG-INFO +54 -12
  2. {taskseam-0.1.1 → taskseam-0.2.0}/README.md +53 -11
  3. {taskseam-0.1.1 → taskseam-0.2.0}/pyproject.toml +1 -1
  4. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam/__init__.py +1 -1
  5. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam/__main__.py +105 -17
  6. taskseam-0.2.0/taskseam/hooks.py +145 -0
  7. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam/mcp.py +90 -14
  8. taskseam-0.2.0/taskseam/render.py +78 -0
  9. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam/store.py +93 -7
  10. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam.egg-info/PKG-INFO +54 -12
  11. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam.egg-info/SOURCES.txt +3 -0
  12. {taskseam-0.1.1 → taskseam-0.2.0}/tests/test_cli.py +4 -0
  13. taskseam-0.2.0/tests/test_continuity_features.py +248 -0
  14. {taskseam-0.1.1 → taskseam-0.2.0}/tests/test_mcp.py +8 -0
  15. {taskseam-0.1.1 → taskseam-0.2.0}/tests/test_store.py +37 -1
  16. {taskseam-0.1.1 → taskseam-0.2.0}/LICENSE +0 -0
  17. {taskseam-0.1.1 → taskseam-0.2.0}/setup.cfg +0 -0
  18. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam/api.py +0 -0
  19. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam/importer.py +0 -0
  20. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam/setup.py +0 -0
  21. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam/workspace.py +0 -0
  22. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam.egg-info/dependency_links.txt +0 -0
  23. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam.egg-info/entry_points.txt +0 -0
  24. {taskseam-0.1.1 → taskseam-0.2.0}/taskseam.egg-info/top_level.txt +0 -0
  25. {taskseam-0.1.1 → taskseam-0.2.0}/tests/test_api.py +0 -0
  26. {taskseam-0.1.1 → taskseam-0.2.0}/tests/test_end_to_end.py +0 -0
  27. {taskseam-0.1.1 → taskseam-0.2.0}/tests/test_importer.py +0 -0
  28. {taskseam-0.1.1 → taskseam-0.2.0}/tests/test_setup.py +0 -0
  29. {taskseam-0.1.1 → taskseam-0.2.0}/tests/test_workspace.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taskseam
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: Local-first task continuity across AI coding agents
5
5
  Author: Sai Sandeep Kantareddy
6
6
  Maintainer: Sai Sandeep Kantareddy
@@ -27,24 +27,53 @@ Description-Content-Type: text/markdown
27
27
  License-File: LICENSE
28
28
  Dynamic: license-file
29
29
 
30
- # TaskSeam
30
+ # 🧵 TaskSeam
31
31
 
32
- **Switch AI. Keep working.**
32
+ ## **Switch AI. Keep working.**
33
33
 
34
- TaskSeam keeps the accepted state of a project available when work moves between Codex, Claude Code, VS Code agents, ChatGPT, and Claude.
34
+ *Local-first task continuity across independent AI coding agents.*
35
35
 
36
- [Website](https://taskseam.github.io/taskseam/) · [Editor setup](https://github.com/TaskSeam/taskseam/blob/main/docs/EDITOR_SETUP.md) · [Quick start](https://github.com/TaskSeam/taskseam/blob/main/docs/QUICKSTART.md) · [Demo](https://github.com/TaskSeam/taskseam/blob/main/docs/DEMO.md) · [Privacy](https://github.com/TaskSeam/taskseam/blob/main/PRIVACY.md)
36
+ TaskSeam carries accepted decisions, active constraints, and unresolved questions between Codex, Claude Code, and VS Code agents. Each project stays local, and each connected agent receives only the changes it has not seen.
37
+
38
+ [Website](https://taskseam.github.io/taskseam/) · [Why TaskSeam](https://github.com/TaskSeam/taskseam/blob/main/docs/WHY_TASKSEAM.md) · [Editor setup](https://github.com/TaskSeam/taskseam/blob/main/docs/EDITOR_SETUP.md) · [Demo](https://github.com/TaskSeam/taskseam/blob/main/docs/DEMO.md) · [Privacy](https://github.com/TaskSeam/taskseam/blob/main/PRIVACY.md)
39
+
40
+ ```mermaid
41
+ flowchart LR
42
+ A["Claude Code<br/>Accept a decision"] --> T["TaskSeam<br/>Current project state"]
43
+ T --> B["Codex<br/>Continue with the decision"]
44
+ B --> C["Codex<br/>Add a constraint"]
45
+ C --> T
46
+ T --> D["Claude Code<br/>Receive only what changed"]
47
+ ```
48
+
49
+ **Local SQLite · Open source · MCP compatible · No hosted account**
37
50
 
38
51
  > **Public alpha:** The local CLI, MCP server, agent plugin, project state, provenance, and per-agent continuation are working. The browser extension is a developer preview.
39
52
 
53
+ ## The problem: context rot
54
+
55
+ Switching AI tools often means reconstructing the task instead of continuing it:
56
+
57
+ 1. Re-explain the project and its current direction.
58
+ 2. Paste long chat histories that consume the next agent's context window.
59
+ 3. Correct suggestions that conflict with decisions or constraints established elsewhere.
60
+
61
+ TaskSeam stores the current task state under the project's `.taskseam/` directory. It shares concise, source-linked state through MCP instead of copying entire conversations between tools.
62
+
40
63
  ## Quick start
41
64
 
42
- Install TaskSeam:
65
+ Install TaskSeam as an isolated command-line application:
43
66
 
44
67
  ```bash
45
68
  pipx install taskseam
46
69
  ```
47
70
 
71
+ Standard pip installation also works:
72
+
73
+ ```bash
74
+ python3 -m pip install taskseam
75
+ ```
76
+
48
77
  Connect the supported agents installed on your computer:
49
78
 
50
79
  ```bash
@@ -64,7 +93,20 @@ Start with this prompt:
64
93
 
65
94
  > Continue this project. What accepted decisions, constraints, and open questions should I know?
66
95
 
67
- There are no routine TaskSeam commands after initialization.
96
+ 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`.
97
+
98
+ ## Everyday commands
99
+
100
+ 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:
101
+
102
+ ```bash
103
+ taskseam show # what every agent will see, in plain text
104
+ taskseam drop 3f9a --reason "Offline mode cut" # retire an item that no longer applies
105
+ taskseam export --agents-md # mirror state into AGENTS.md for non-MCP agents
106
+ taskseam export --history # deterministic JSON, including superseded items
107
+ ```
108
+
109
+ Item IDs accept any unique prefix of four or more characters.
68
110
 
69
111
  ## What changes for the user?
70
112
 
@@ -126,11 +168,11 @@ The [five-minute demo](https://github.com/TaskSeam/taskseam/blob/main/docs/DEMO.
126
168
 
127
169
  The [public roadmap](https://github.com/TaskSeam/taskseam/blob/main/ROADMAP.md) tracks the current priorities:
128
170
 
129
- 1. Validate clean installation across supported operating systems.
130
- 2. Publish the Python package to PyPI.
131
- 3. Package and submit the browser extension.
132
- 4. Improve automatic task matching and correction.
133
- 5. Publish repeatable continuity evaluations.
171
+ 1. Retry-safe delivery: acknowledge exactly what an agent received.
172
+ 2. Publish repeatable continuity evaluations.
173
+ 3. Validate clean installation across supported operating systems.
174
+ 4. Package and submit the browser extension.
175
+ 5. Improve automatic task matching and correction.
134
176
 
135
177
  ## Development
136
178
 
@@ -1,21 +1,50 @@
1
- # TaskSeam
1
+ # 🧵 TaskSeam
2
2
 
3
- **Switch AI. Keep working.**
3
+ ## **Switch AI. Keep working.**
4
4
 
5
- TaskSeam keeps the accepted state of a project available when work moves between Codex, Claude Code, VS Code agents, ChatGPT, and Claude.
5
+ *Local-first task continuity across independent AI coding agents.*
6
6
 
7
- [Website](https://taskseam.github.io/taskseam/) · [Editor setup](https://github.com/TaskSeam/taskseam/blob/main/docs/EDITOR_SETUP.md) · [Quick start](https://github.com/TaskSeam/taskseam/blob/main/docs/QUICKSTART.md) · [Demo](https://github.com/TaskSeam/taskseam/blob/main/docs/DEMO.md) · [Privacy](https://github.com/TaskSeam/taskseam/blob/main/PRIVACY.md)
7
+ TaskSeam carries accepted decisions, active constraints, and unresolved questions between Codex, Claude Code, and VS Code agents. Each project stays local, and each connected agent receives only the changes it has not seen.
8
+
9
+ [Website](https://taskseam.github.io/taskseam/) · [Why TaskSeam](https://github.com/TaskSeam/taskseam/blob/main/docs/WHY_TASKSEAM.md) · [Editor setup](https://github.com/TaskSeam/taskseam/blob/main/docs/EDITOR_SETUP.md) · [Demo](https://github.com/TaskSeam/taskseam/blob/main/docs/DEMO.md) · [Privacy](https://github.com/TaskSeam/taskseam/blob/main/PRIVACY.md)
10
+
11
+ ```mermaid
12
+ flowchart LR
13
+ A["Claude Code<br/>Accept a decision"] --> T["TaskSeam<br/>Current project state"]
14
+ T --> B["Codex<br/>Continue with the decision"]
15
+ B --> C["Codex<br/>Add a constraint"]
16
+ C --> T
17
+ T --> D["Claude Code<br/>Receive only what changed"]
18
+ ```
19
+
20
+ **Local SQLite · Open source · MCP compatible · No hosted account**
8
21
 
9
22
  > **Public alpha:** The local CLI, MCP server, agent plugin, project state, provenance, and per-agent continuation are working. The browser extension is a developer preview.
10
23
 
24
+ ## The problem: context rot
25
+
26
+ Switching AI tools often means reconstructing the task instead of continuing it:
27
+
28
+ 1. Re-explain the project and its current direction.
29
+ 2. Paste long chat histories that consume the next agent's context window.
30
+ 3. Correct suggestions that conflict with decisions or constraints established elsewhere.
31
+
32
+ TaskSeam stores the current task state under the project's `.taskseam/` directory. It shares concise, source-linked state through MCP instead of copying entire conversations between tools.
33
+
11
34
  ## Quick start
12
35
 
13
- Install TaskSeam:
36
+ Install TaskSeam as an isolated command-line application:
14
37
 
15
38
  ```bash
16
39
  pipx install taskseam
17
40
  ```
18
41
 
42
+ Standard pip installation also works:
43
+
44
+ ```bash
45
+ python3 -m pip install taskseam
46
+ ```
47
+
19
48
  Connect the supported agents installed on your computer:
20
49
 
21
50
  ```bash
@@ -35,7 +64,20 @@ Start with this prompt:
35
64
 
36
65
  > Continue this project. What accepted decisions, constraints, and open questions should I know?
37
66
 
38
- There are no routine TaskSeam commands after initialization.
67
+ 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`.
68
+
69
+ ## Everyday commands
70
+
71
+ 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:
72
+
73
+ ```bash
74
+ taskseam show # what every agent will see, in plain text
75
+ taskseam drop 3f9a --reason "Offline mode cut" # retire an item that no longer applies
76
+ taskseam export --agents-md # mirror state into AGENTS.md for non-MCP agents
77
+ taskseam export --history # deterministic JSON, including superseded items
78
+ ```
79
+
80
+ Item IDs accept any unique prefix of four or more characters.
39
81
 
40
82
  ## What changes for the user?
41
83
 
@@ -97,11 +139,11 @@ The [five-minute demo](https://github.com/TaskSeam/taskseam/blob/main/docs/DEMO.
97
139
 
98
140
  The [public roadmap](https://github.com/TaskSeam/taskseam/blob/main/ROADMAP.md) tracks the current priorities:
99
141
 
100
- 1. Validate clean installation across supported operating systems.
101
- 2. Publish the Python package to PyPI.
102
- 3. Package and submit the browser extension.
103
- 4. Improve automatic task matching and correction.
104
- 5. Publish repeatable continuity evaluations.
142
+ 1. Retry-safe delivery: acknowledge exactly what an agent received.
143
+ 2. Publish repeatable continuity evaluations.
144
+ 3. Validate clean installation across supported operating systems.
145
+ 4. Package and submit the browser extension.
146
+ 5. Improve automatic task matching and correction.
105
147
 
106
148
  ## Development
107
149
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "taskseam"
7
- version = "0.1.1"
7
+ version = "0.2.0"
8
8
  description = "Local-first task continuity across AI coding agents"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -1,3 +1,3 @@
1
1
  """Local task state and handoff tools."""
2
2
 
3
- __version__ = "0.1.1"
3
+ __version__ = "0.2.0"
@@ -68,6 +68,8 @@ def parser():
68
68
  setup.add_argument("tool", nargs="?", choices=("codex", "claude-code"),
69
69
  help="Configure one tool; omit to configure every detected tool")
70
70
  setup.add_argument("--dry-run", action="store_true")
71
+ setup.add_argument("--no-hooks", action="store_true",
72
+ help="Skip the session-start hook that loads project state automatically")
71
73
  commands.add_parser("prompt", help="Print the prompt for creating an import packet")
72
74
  import_command = commands.add_parser("import", help="Preview or apply a TaskSeam state packet")
73
75
  import_command.add_argument("path", nargs="?", help="JSON file; omit to read standard input")
@@ -84,12 +86,52 @@ def parser():
84
86
  handoff = commands.add_parser("handoff", help="Deliver changes since a target's last handoff")
85
87
  handoff.add_argument("--to", required=True, dest="target")
86
88
  handoff.add_argument("--task-id", help="Defaults to the active workspace task")
89
+ handoff.add_argument("--full", action="store_true",
90
+ help="Also include current state for a fresh chat or lost context")
91
+ show = commands.add_parser("show", help="Print the active task's state in readable form")
92
+ show.add_argument("task_id", nargs="?", help="Defaults to the active workspace task")
93
+ drop = commands.add_parser("drop", help="Retire an item that no longer applies")
94
+ drop.add_argument("item_id", help="Item ID or unique prefix")
95
+ drop.add_argument("--reason", required=True)
96
+ drop.add_argument("--source", default="manual")
97
+ export = commands.add_parser("export", help="Write deterministic JSON or Markdown state")
98
+ export.add_argument("--format", choices=("json", "markdown"), default="json")
99
+ export.add_argument("--history", action="store_true",
100
+ help="Include superseded, resolved, and retired items (JSON only)")
101
+ destination = export.add_mutually_exclusive_group()
102
+ destination.add_argument("--output", "-o", help="Write to a file instead of standard output")
103
+ destination.add_argument("--agents-md", nargs="?", const="AGENTS.md", metavar="PATH",
104
+ help="Maintain a TaskSeam block inside AGENTS.md (or PATH)")
105
+ export.add_argument("--task-id", help="Defaults to the active workspace task")
106
+ hook = commands.add_parser("hook", help="Agent session hooks")
107
+ hook_sub = hook.add_subparsers(dest="action", required=True)
108
+ hook_sub.add_parser("session-start", help="Print state for a SessionStart hook (reads hook JSON)")
109
+ hook_install = hook_sub.add_parser("install", help="Install the SessionStart hook")
110
+ hook_install.add_argument("tool", nargs="?", choices=("codex", "claude-code"))
111
+ hook_install.add_argument("--dry-run", action="store_true")
87
112
  return p
88
113
 
89
114
 
115
+ def _task_or_active(task_id, workspace):
116
+ task_id = task_id or (active_task(workspace) if workspace else None)
117
+ if not task_id:
118
+ raise ValueError("Provide a task ID or run this command in a TaskSeam workspace")
119
+ return task_id
120
+
121
+
122
+ def _agents_md_block(task, items):
123
+ from .render import brief
124
+ body = brief(task, items, header=False)
125
+ body = "\n".join("#" + line if line.startswith("## ") else line for line in body.splitlines())
126
+ return "## Project state (TaskSeam: {})\n\n{}\n".format(task["title"], body)
127
+
128
+
90
129
  def main(argv=None):
91
130
  args = parser().parse_args(argv)
92
131
  try:
132
+ if args.command == "hook" and args.action == "session-start":
133
+ from .hooks import session_start
134
+ return session_start()
93
135
  if args.command == "init":
94
136
  title = args.title or Path.cwd().name
95
137
 
@@ -129,6 +171,10 @@ def main(argv=None):
129
171
  result = setup_claude(sys.executable, args.dry_run)
130
172
  else:
131
173
  result = setup_detected(sys.executable, args.dry_run)
174
+ if not args.no_hooks:
175
+ from .hooks import install_detected
176
+ tools = {"codex": ["codex"], "claude-code": ["claude-code"]}.get(args.tool)
177
+ result["session_hooks"] = install_detected(sys.executable, args.dry_run, tools)
132
178
  print(json.dumps(result, indent=2))
133
179
  return 0
134
180
  if args.command == "import":
@@ -164,6 +210,11 @@ def main(argv=None):
164
210
  from .mcp import run
165
211
  run(args.db, task_id=active_task(workspace) if workspace else None)
166
212
  return 0
213
+ if args.command == "hook":
214
+ from .hooks import install_detected
215
+ tools = [args.tool] if args.tool else None
216
+ print(json.dumps(install_detected(sys.executable, args.dry_run, tools), indent=2))
217
+ return 0
167
218
  if args.command == "version":
168
219
  from . import __version__
169
220
  print(__version__)
@@ -180,29 +231,66 @@ def main(argv=None):
180
231
  elif args.command == "event":
181
232
  result = {"event_id": store.add_event(args.task_id, args.source, args.body)}
182
233
  elif args.command == "item":
234
+ supersedes = args.supersedes and store.resolve_item_id(args.supersedes, args.task_id)
183
235
  result = {"item_id": store.add_item(args.task_id, args.kind, args.body,
184
- args.source, args.supersedes)}
185
- elif args.command == "record":
186
- if not workspace:
187
- raise ValueError("No TaskSeam workspace found; run 'taskseam init'")
188
- result = {"item_id": store.add_item(active_task(workspace), args.kind, args.body,
189
- args.source, args.supersedes)}
190
- elif args.command == "resolve":
191
- if not workspace:
192
- raise ValueError("No TaskSeam workspace found; run 'taskseam init'")
193
- result = {"item_id": store.resolve_question(active_task(workspace), args.question_id,
194
- args.decision, args.source, args.supersedes),
195
- "resolved_question": args.question_id}
196
- elif args.command == "supersede":
236
+ args.source, supersedes)}
237
+ elif args.command in ("record", "resolve", "supersede", "drop"):
197
238
  if not workspace:
198
239
  raise ValueError("No TaskSeam workspace found; run 'taskseam init'")
199
- store.set_supersession(active_task(workspace), args.old_item_id, args.new_item_id)
200
- result = {"superseded": args.old_item_id, "replacement": args.new_item_id}
240
+ task_id = active_task(workspace)
241
+
242
+ def ref(value):
243
+ return store.resolve_item_id(value, task_id) if value else None
244
+
245
+ if args.command == "record":
246
+ result = {"item_id": store.add_item(task_id, args.kind, args.body,
247
+ args.source, ref(args.supersedes))}
248
+ elif args.command == "resolve":
249
+ question_id = ref(args.question_id)
250
+ result = {"item_id": store.resolve_question(task_id, question_id, args.decision,
251
+ args.source, ref(args.supersedes)),
252
+ "resolved_question": question_id}
253
+ elif args.command == "supersede":
254
+ old, new = ref(args.old_item_id), ref(args.new_item_id)
255
+ store.set_supersession(task_id, old, new)
256
+ result = {"superseded": old, "replacement": new}
257
+ else:
258
+ result = store.retire_item(task_id, ref(args.item_id), args.reason, args.source)
259
+ elif args.command == "show":
260
+ from .render import brief
261
+ context = store.context(_task_or_active(args.task_id, workspace))
262
+ print(brief(context["task"], context["items"]), end="")
263
+ return 0
264
+ elif args.command == "export":
265
+ from .render import brief, splice_agents_md
266
+ task_id = _task_or_active(args.task_id, workspace)
267
+ if args.history and args.format != "json":
268
+ raise ValueError("--history is only available with --format json")
269
+ if args.agents_md:
270
+ context = store.context(task_id)
271
+ target = Path(args.agents_md)
272
+ existing = target.read_text(encoding="utf-8") if target.exists() else ""
273
+ target.write_text(splice_agents_md(
274
+ existing, _agents_md_block(context["task"], context["items"])), encoding="utf-8")
275
+ print("taskseam: updated {}. It is usually committed to Git; review the block "
276
+ "before sharing.".format(target), file=sys.stderr)
277
+ return 0
278
+ if args.format == "json":
279
+ text = json.dumps(store.export(task_id, history=args.history), indent=2,
280
+ sort_keys=True) + "\n"
281
+ else:
282
+ snapshot = store.export(task_id)
283
+ text = brief(snapshot["task"], snapshot["items"])
284
+ if args.output:
285
+ Path(args.output).write_text(text, encoding="utf-8")
286
+ else:
287
+ sys.stdout.write(text)
288
+ return 0
201
289
  elif args.command == "handoff":
202
290
  task_id = args.task_id or (active_task(workspace) if workspace else None)
203
291
  if not task_id:
204
292
  raise ValueError("Provide a task ID or run this command in a TaskSeam workspace")
205
- result = store.handoff(task_id, args.target)
293
+ result = store.handoff(task_id, args.target, full=args.full)
206
294
  elif args.command == "checkpoint":
207
295
  task_id = args.task_id or (active_task(workspace) if workspace else None)
208
296
  if not task_id:
@@ -216,7 +304,7 @@ def main(argv=None):
216
304
  raise ValueError("Provide a task ID or run this command in a TaskSeam workspace")
217
305
  result = store.context(task_id)
218
306
  else:
219
- result = store.explain(args.item_id)
307
+ result = store.explain(store.resolve_item_id(args.item_id))
220
308
  print(json.dumps(result, indent=2))
221
309
  return 0
222
310
  finally:
@@ -0,0 +1,145 @@
1
+ """Session-start hooks that load TaskSeam state without relying on a tool call.
2
+
3
+ Claude Code and Codex both run SessionStart hooks and add their plain stdout to
4
+ the model's context. TaskSeam uses that to put current project state into every
5
+ new, cleared, compacted, or resumed session. The hook is read-only: it does not
6
+ advance any agent's delivery position, so ``taskseam_continue`` deltas still work.
7
+ """
8
+
9
+ import json
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ from .render import brief
17
+ from .store import Store
18
+ from .workspace import active_task, database_path, find_workspace
19
+
20
+ HOOK_MARKER = "taskseam hook session-start"
21
+ MATCHER = "startup|resume|clear|compact"
22
+ # Claude Code caps hook context at 10,000 characters; Codex defaults to about
23
+ # 2,500 tokens. Stay below both so the brief is never truncated by the host.
24
+ BUDGET = 6000
25
+ GUIDANCE = ("TaskSeam is connected for this project. When the user explicitly accepts a decision, "
26
+ "sets a constraint, or leaves a material question open, save it with taskseam_record "
27
+ "(or taskseam_resolve / taskseam_retire); call taskseam_continue for changes made by "
28
+ "other agents during this session.")
29
+
30
+
31
+ def session_start(stdin=None, stdout=None):
32
+ """Print the active task's brief; stay silent outside a TaskSeam workspace."""
33
+ stdin = stdin or sys.stdin
34
+ stdout = stdout or sys.stdout
35
+ payload = {}
36
+ try:
37
+ if not stdin.isatty():
38
+ raw = stdin.read()
39
+ payload = json.loads(raw) if raw.strip() else {}
40
+ except (ValueError, OSError):
41
+ payload = {}
42
+ cwd = payload.get("cwd") if isinstance(payload, dict) else None
43
+ try:
44
+ workspace = find_workspace(cwd or os.getcwd())
45
+ if not workspace:
46
+ return 0
47
+ store = Store(database_path(workspace))
48
+ try:
49
+ context = store.context(active_task(workspace))
50
+ finally:
51
+ store.close()
52
+ except Exception as exc: # A hook must never block the user's session.
53
+ print("taskseam hook: " + str(exc), file=sys.stderr)
54
+ return 0
55
+ stdout.write(brief(context["task"], context["items"], budget=BUDGET))
56
+ stdout.write("\n" + GUIDANCE + "\n")
57
+ stdout.flush()
58
+ return 0
59
+
60
+
61
+ def hook_command(python_executable=None):
62
+ python = python_executable or sys.executable
63
+ args = [python, "-m", "taskseam", "hook", "session-start"]
64
+ if os.name == "nt":
65
+ return subprocess.list2cmdline(args)
66
+ import shlex
67
+ return " ".join(shlex.quote(arg) for arg in args)
68
+
69
+
70
+ def claude_settings_path():
71
+ return Path.home() / ".claude" / "settings.json"
72
+
73
+
74
+ def codex_hooks_path():
75
+ return Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex") / "hooks.json"
76
+
77
+
78
+ def install(path, python_executable=None, dry_run=False):
79
+ """Add or refresh the TaskSeam SessionStart hook in a hooks JSON file.
80
+
81
+ Claude Code's settings.json and Codex's hooks.json share this structure.
82
+ Unrelated settings and hooks are preserved; an existing TaskSeam entry is
83
+ updated in place so reinstalling never duplicates it.
84
+ """
85
+ path = Path(path)
86
+ command = hook_command(python_executable)
87
+ original = path.read_text(encoding="utf-8") if path.exists() else ""
88
+ try:
89
+ data = json.loads(original) if original.strip() else {}
90
+ except json.JSONDecodeError as exc:
91
+ raise ValueError("Cannot update {}: invalid JSON ({})".format(path, exc)) from exc
92
+ if not isinstance(data, dict):
93
+ raise ValueError("Cannot update {}: expected a JSON object".format(path))
94
+ hooks = data.setdefault("hooks", {})
95
+ if not isinstance(hooks, dict):
96
+ raise ValueError("Cannot update {}: 'hooks' must be an object".format(path))
97
+ groups = hooks.setdefault("SessionStart", [])
98
+ if not isinstance(groups, list):
99
+ raise ValueError("Cannot update {}: 'hooks.SessionStart' must be a list".format(path))
100
+ entry = {"type": "command", "command": command, "timeout": 10}
101
+ status = "installed"
102
+ for group in groups:
103
+ for handler in (group.get("hooks") or []) if isinstance(group, dict) else []:
104
+ if isinstance(handler, dict) and HOOK_MARKER in str(handler.get("command", "")):
105
+ status = "unchanged" if handler.get("command") == command else "updated"
106
+ handler["command"] = command
107
+ break
108
+ else:
109
+ continue
110
+ break
111
+ else:
112
+ groups.append({"matcher": MATCHER, "hooks": [entry]})
113
+ result = {"path": str(path), "status": status, "command": command}
114
+ if dry_run or status == "unchanged":
115
+ result["written"] = False
116
+ return result
117
+ path.parent.mkdir(parents=True, exist_ok=True)
118
+ if original:
119
+ backup = path.with_name(path.name + ".taskseam-backup")
120
+ if not backup.exists():
121
+ backup.write_text(original, encoding="utf-8")
122
+ result["backup"] = str(backup)
123
+ temporary = path.with_name(path.name + ".taskseam-tmp")
124
+ temporary.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
125
+ os.replace(str(temporary), str(path))
126
+ result["written"] = True
127
+ return result
128
+
129
+
130
+ def install_detected(python_executable=None, dry_run=False, tools=None):
131
+ """Install the hook for each supported agent found on PATH."""
132
+ targets = (("claude-code", "claude", claude_settings_path),
133
+ ("codex", "codex", codex_hooks_path))
134
+ installed, skipped = [], []
135
+ for name, executable, locate in targets:
136
+ if tools and name not in tools:
137
+ continue
138
+ if not shutil.which(executable):
139
+ skipped.append({"tool": name, "reason": "not found on PATH"})
140
+ continue
141
+ result = install(locate(), python_executable, dry_run)
142
+ if name == "codex":
143
+ result["note"] = "Codex runs new hooks only after you review and trust them with /hooks"
144
+ installed.append({"tool": name, **result})
145
+ return {"hooks": installed, "skipped": skipped}