-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask
More file actions
executable file
·711 lines (577 loc) · 24.9 KB
/
Copy pathtask
File metadata and controls
executable file
·711 lines (577 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
#!/usr/bin/env python3
"""File-backed task manager with collision-free, concurrent-safe IDs and agent locks.
ID scheme (task 1206)
=====================
Task IDs are ``<NNNN>-<TOKEN>-<slug>`` where:
* ``NNNN`` is a zero-padded, monotonically-increasing *sequence hint* (human-friendly,
sortable, the number agents cite in commits e.g. "task 1217").
* ``TOKEN`` is a short collision-resistant base36 token (timestamp + randomness).
* ``slug`` is a filesystem-safe slug derived from the title.
Why a token and not a bare counter? Agents run in **independent git worktrees**, each with
its own ``.tasks/.counter`` and its own ``.mutex``. A per-file lock (``fcntl.flock``) only
serializes creates *within one worktree*; two worktrees read the same committed counter and
mint the SAME ``NNNN`` -> duplicate IDs that collide when the worktrees merge to main. There
is no shared lock at create time across worktrees (they only converge at git-merge time), so
a pure counter can never be collision-free here. The ``TOKEN`` guarantees uniqueness even
when two worktrees pick the same ``NNNN``: the full IDs differ, the filenames differ, and the
two task files merge cleanly with no git conflict. The ``NNNN`` is kept only as a sortable,
citable hint -- the ``TOKEN`` is the authority for uniqueness.
Lookups (show/update/acquire/delete/release/renew) resolve an exact id first; a bare prefix
(e.g. ``1217`` or a partial id) resolves only if it matches exactly one task -- an ambiguous
prefix FAILS LOUDLY and lists the matches, so an agent can never silently act on the wrong
task.
"""
from __future__ import annotations
import argparse
import fcntl
import hashlib
import json
import os
import re
import secrets
import shutil
import socket
import sys
import time
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent
TASKS_DIR = ROOT / ".tasks"
LOCKS_DIR = TASKS_DIR / "locks"
MUTEX_FILE = TASKS_DIR / ".mutex"
COUNTER_FILE = TASKS_DIR / ".counter"
DEFAULT_TTL = 3600
ID_WIDTH = 4
# A modern id: NNNN-TOKEN-slug. TOKEN is exactly TOKEN_LEN base36 chars and ALWAYS starts
# with a digit, which makes it unambiguously distinguishable from a slug word (title-derived
# slug words effectively never start with a digit). This guards migration's idempotency
# detection: a legacy id like ``1213-golden-...`` is NOT mistaken for an already-tokenized id.
TOKEN_LEN = 6
ID_FULL_RE = re.compile(
r"^(\d{" + str(ID_WIDTH) + r"})-(\d[0-9a-z]{" + str(TOKEN_LEN - 1) + r"})-(.*)$"
)
# A legacy id (pre-1206): NNNN-slug (no token).
ID_LEGACY_RE = re.compile(r"^(\d{" + str(ID_WIDTH) + r"})-(.*)$")
ID_PREFIX_RE = re.compile(r"^\d{" + str(ID_WIDTH) + r"}-")
_BASE36 = "0123456789abcdefghijklmnopqrstuvwxyz"
STATUSES = frozenset({"open", "in_progress", "done", "cancelled"})
EFFORTS = frozenset({"default", "high", "extreme"})
PRIORITIES = frozenset({"low", "medium", "high"})
PRIORITY_ORDER = {"high": 0, "medium": 1, "low": 2}
EFFORT_MODELS = {"default": "claude-sonnet-4-6", "high": "claude-opus-4-8", "extreme": "claude-fable-5"}
def die(message: str) -> None:
print(f"task: {message}", file=sys.stderr)
raise SystemExit(1)
def now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def parse_iso(value: str) -> datetime:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
def default_holder() -> str:
agent_id = os.environ.get("TASK_AGENT_ID")
if agent_id:
return agent_id
return f"{os.environ.get('USER', 'unknown')}@{socket.gethostname()}"
def slugify(text: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
return (slug[:48] or "task")
def normalize_slug(raw: str) -> str:
"""Strip an existing id prefix (NNNN- or NNNN-TOKEN-) and return a safe slug."""
raw = raw.strip()
full = ID_FULL_RE.match(raw)
if full:
raw = full.group(3)
else:
raw = ID_PREFIX_RE.sub("", raw)
slug = re.sub(r"[^a-z0-9-]+", "-", raw.lower()).strip("-")
return slug[:48] or "task"
def _base36(n: int, width: int) -> str:
if n <= 0:
return "0" * width
chars = []
while n > 0:
n, rem = divmod(n, 36)
chars.append(_BASE36[rem])
s = "".join(reversed(chars))
return s[-width:] if len(s) >= width else s.rjust(width, "0")
def new_token() -> str:
"""A short, time-sortable, collision-resistant base36 token.
First 4 chars: the low 4 base36 digits of the current ms timestamp (monotone within a
~36^4 ms window, so freshly-created ids sort by time). Remaining chars:
cryptographically-random base36 -- two worktrees minting the same NNNN in the same
millisecond still get distinct ids with overwhelming probability.
"""
ms = int(time.time() * 1000)
time_part = _base36(ms, 4)[-4:]
rand_part = "".join(secrets.choice(_BASE36) for _ in range(TOKEN_LEN - 4))
return _force_leading_digit(time_part + rand_part)
def _force_leading_digit(token: str) -> str:
"""Ensure the token starts with a digit (see ID_FULL_RE)."""
if token and token[0].isdigit():
return token
# Map the leading base36 char into the digit range deterministically.
return str(_BASE36.index(token[0]) % 10) + token[1:]
def make_task_id(number: int, token: str, slug: str) -> str:
return f"{number:0{ID_WIDTH}d}-{token}-{slug}"
def id_sort_key(task_id: str) -> tuple[int, str]:
"""Sort by numeric prefix then full id, for stable time-ish ordering."""
full = ID_FULL_RE.match(task_id)
if full:
return (int(full.group(1)), task_id)
legacy = ID_LEGACY_RE.match(task_id)
if legacy:
return (int(legacy.group(1)), task_id)
return (10**9, task_id)
def read_counter() -> int:
if not COUNTER_FILE.is_file():
return 1
try:
return max(1, int(COUNTER_FILE.read_text(encoding="utf-8").strip()))
except ValueError:
return 1
def write_counter(value: int) -> None:
COUNTER_FILE.write_text(f"{max(1, value)}\n", encoding="utf-8")
def max_existing_number() -> int:
"""Highest NNNN seen across all task files (counter is only a per-worktree hint)."""
highest = 0
for path in TASKS_DIR.glob("*.json"):
m = ID_LEGACY_RE.match(path.stem)
if m:
highest = max(highest, int(m.group(1)))
return highest
def allocate_task_number() -> int:
"""Sequence hint = max(counter, highest-on-disk) + 1.
The hint is NOT relied on for uniqueness (the token guarantees that); we just keep it
monotone within a worktree and never below what is already on disk.
"""
number = max(read_counter(), max_existing_number() + 1)
write_counter(number + 1)
return number
def task_path(task_id: str) -> Path:
return TASKS_DIR / f"{task_id}.json"
def lock_dir(task_id: str) -> Path:
return LOCKS_DIR / task_id
def lock_meta_path(task_id: str) -> Path:
return lock_dir(task_id) / "meta.json"
def ensure_dirs() -> None:
TASKS_DIR.mkdir(parents=True, exist_ok=True)
LOCKS_DIR.mkdir(parents=True, exist_ok=True)
@contextmanager
def global_mutex():
ensure_dirs()
with open(MUTEX_FILE, "a", encoding="utf-8") as mutex:
fcntl.flock(mutex.fileno(), fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(mutex.fileno(), fcntl.LOCK_UN)
def all_task_ids() -> list[str]:
return sorted((p.stem for p in TASKS_DIR.glob("*.json")), key=id_sort_key)
def resolve_id(raw: str) -> str:
"""Resolve a user-supplied id or bare prefix to exactly one task id.
Exact id match always wins. Otherwise a prefix that matches exactly one task resolves;
a prefix matching multiple tasks FAILS LOUDLY listing the matches, and no match errors.
Accepts a bare numeric prefix ("1217") or any leading substring of an id.
"""
raw = raw.strip()
if not raw:
die("empty task id")
# Exact id (filename) match wins outright.
if task_path(raw).is_file():
return raw
ids = all_task_ids()
# A bare numeric prefix like "1217" matches the NNNN component.
if re.fullmatch(r"\d{1,%d}" % ID_WIDTH, raw):
num = int(raw)
matches = [tid for tid in ids if id_sort_key(tid)[0] == num]
else:
matches = [tid for tid in ids if tid == raw or tid.startswith(raw)]
if not matches:
die(f"task not found: {raw}")
if len(matches) > 1:
listing = "\n ".join(matches)
die(
f"ambiguous task id '{raw}' matches {len(matches)} tasks; "
f"specify the full id:\n {listing}"
)
return matches[0]
def read_task(task_id: str) -> dict[str, Any]:
path = task_path(task_id)
if not path.is_file():
die(f"task not found: {task_id}")
return json.loads(path.read_text(encoding="utf-8"))
def write_task(task: dict[str, Any]) -> None:
path = task_path(task["id"])
path.write_text(json.dumps(task, indent=2) + "\n", encoding="utf-8")
def read_lock_meta(task_id: str) -> dict[str, Any] | None:
path = lock_meta_path(task_id)
if not path.is_file():
return None
return json.loads(path.read_text(encoding="utf-8"))
def lock_is_expired(meta: dict[str, Any]) -> bool:
expires = meta.get("expires_at")
if not expires:
return True
try:
return datetime.now(timezone.utc) >= parse_iso(expires)
except ValueError:
return False
def active_lock(task_id: str) -> dict[str, Any] | None:
meta = read_lock_meta(task_id)
if meta is None:
return None
if lock_is_expired(meta):
return None
return meta
def cleanup_stale_lock(task_id: str) -> bool:
"""Remove expired or corrupt lock. Returns True if a lock dir was removed."""
directory = lock_dir(task_id)
if not directory.is_dir():
return False
meta = read_lock_meta(task_id)
if meta is None or lock_is_expired(meta):
shutil.rmtree(directory, ignore_errors=True)
return True
return False
def write_lock_meta(task_id: str, holder: str, ttl: int) -> dict[str, Any]:
now = datetime.now(timezone.utc)
expires = now + timedelta(seconds=ttl)
meta = {
"task_id": task_id,
"holder": holder,
"pid": os.getpid(),
"hostname": socket.gethostname(),
"acquired_at": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
"expires_at": expires.strftime("%Y-%m-%dT%H:%M:%SZ"),
"ttl_seconds": ttl,
}
directory = lock_dir(task_id)
directory.mkdir(parents=True, exist_ok=True)
lock_meta_path(task_id).write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
return meta
def task_with_lock(task_id: str) -> dict[str, Any]:
task = read_task(task_id)
task["lock"] = active_lock(task_id)
return task
def cmd_create(args: argparse.Namespace) -> None:
with global_mutex():
number = allocate_task_number()
slug = normalize_slug(args.id) if args.id else slugify(args.title)
# The token guarantees uniqueness; retry on the astronomically-unlikely clash.
for _ in range(8):
token = new_token()
task_id = make_task_id(number, token, slug)
if not task_path(task_id).exists():
break
else:
die("failed to allocate a unique task id")
ts = now_iso()
task: dict[str, Any] = {
"id": task_id,
"title": args.title,
"description": args.description or "",
"status": args.status,
"effort": args.effort,
"priority": args.priority,
"created_at": ts,
"updated_at": ts,
}
write_task(task)
print(task_id)
def priority_sort_key(task: dict[str, Any]) -> int:
return PRIORITY_ORDER.get(task.get("priority", ""), 3)
def cmd_list(args: argparse.Namespace) -> None:
ensure_dirs()
statuses: frozenset[str] | None = None
if args.status:
requested = {s.strip() for s in args.status.split(",")}
invalid = requested - STATUSES
if invalid:
die(f"invalid status(es): {', '.join(sorted(invalid))}. valid: {', '.join(sorted(STATUSES))}")
statuses = frozenset(requested)
tasks = []
for path in sorted(TASKS_DIR.glob("*.json"), key=lambda p: id_sort_key(p.stem)):
task = json.loads(path.read_text(encoding="utf-8"))
if statuses is not None and task.get("status") not in statuses:
continue
if args.priority and task.get("priority") != args.priority:
continue
if args.effort and task.get("effort") != args.effort:
continue
task["lock"] = active_lock(task["id"])
tasks.append(task)
# Stable sort: priority first, falling back to chronological id order.
tasks.sort(key=lambda t: id_sort_key(t["id"]))
tasks.sort(key=priority_sort_key)
if args.json:
print(json.dumps(tasks, indent=2))
return
if not tasks:
print("No tasks.")
return
print(f"{'ID':<56} {'STATUS':<12} {'PRI':<8} {'EFFORT':<10} {'LOCK':<24} TITLE")
print("-" * 130)
for task in tasks:
lock = task.get("lock")
lock_str = lock["holder"] if lock else "-"
title = task.get("title", "")[:40]
pri = task.get("priority") or "-"
effort = task.get("effort") or "-"
print(f"{task['id']:<56} {task.get('status', ''):<12} {pri:<8} {effort:<10} {lock_str:<24} {title}")
def cmd_show(args: argparse.Namespace) -> None:
ensure_dirs()
task = task_with_lock(resolve_id(args.id))
if args.json:
print(json.dumps(task, indent=2))
return
print(f"ID: {task['id']}")
print(f"Title: {task.get('title', '')}")
print(f"Status: {task.get('status', '')}")
effort = task.get("effort") or "default"
model = EFFORT_MODELS.get(effort, "")
print(f"Effort: {effort} ({model})")
print(f"Priority: {task.get('priority') or '-'}")
print(f"Created: {task.get('created_at', '')}")
print(f"Updated: {task.get('updated_at', '')}")
desc = task.get("description") or ""
if desc:
print(f"Description: {desc}")
lock = task.get("lock")
if lock:
print(f"Lock holder: {lock.get('holder')} (expires {lock.get('expires_at')})")
else:
print("Lock: none")
def cmd_update(args: argparse.Namespace) -> None:
if not any([args.title, args.description is not None, args.status, args.effort, args.priority]):
die("update requires at least one field")
with global_mutex():
task_id = resolve_id(args.id)
task = read_task(task_id)
if args.title:
task["title"] = args.title
if args.description is not None:
task["description"] = args.description
if args.status:
task["status"] = args.status
if args.effort:
task["effort"] = args.effort
if args.priority:
task["priority"] = args.priority
task["updated_at"] = now_iso()
write_task(task)
print(f"updated: {task_id}")
def cmd_delete(args: argparse.Namespace) -> None:
with global_mutex():
task_id = resolve_id(args.id)
read_task(task_id)
directory = lock_dir(task_id)
if directory.is_dir() and not cleanup_stale_lock(task_id):
if not args.force:
die("task is locked; use --force to delete anyway")
shutil.rmtree(directory, ignore_errors=True)
task_path(task_id).unlink(missing_ok=True)
print(f"deleted: {task_id}")
def cmd_acquire(args: argparse.Namespace) -> None:
holder = args.holder or default_holder()
with global_mutex():
task_id = resolve_id(args.id)
task = read_task(task_id)
directory = lock_dir(task_id)
if directory.is_dir():
if cleanup_stale_lock(task_id):
pass
else:
current = read_lock_meta(task_id)
current_holder = current.get("holder", "") if current else ""
if current_holder == holder:
write_lock_meta(task_id, holder, args.ttl)
print(f"lock renewed for existing holder: {holder}")
return
die(f"task locked by: {current_holder}")
try:
directory.mkdir(parents=False, exist_ok=False)
except FileExistsError:
die(f"failed to acquire lock (contention on {task_id})")
write_lock_meta(task_id, holder, args.ttl)
if task.get("status") == "open":
task["status"] = "in_progress"
task["updated_at"] = now_iso()
write_task(task)
print(f"acquired: {task_id} (holder={holder}, ttl={args.ttl}s)")
def cmd_release(args: argparse.Namespace) -> None:
holder = args.holder or default_holder()
with global_mutex():
task_id = resolve_id(args.id)
directory = lock_dir(task_id)
if not directory.is_dir():
die(f"no lock held on: {task_id}")
if not args.force:
current = read_lock_meta(task_id)
current_holder = current.get("holder", "") if current else ""
if current_holder != holder:
die(f"lock held by {current_holder}, not {holder}")
shutil.rmtree(directory, ignore_errors=True)
print(f"released: {task_id}")
def cmd_renew(args: argparse.Namespace) -> None:
holder = args.holder or default_holder()
with global_mutex():
task_id = resolve_id(args.id)
directory = lock_dir(task_id)
if not directory.is_dir():
die(f"no lock held on: {task_id}")
current = read_lock_meta(task_id)
current_holder = current.get("holder", "") if current else ""
if current_holder != holder:
die(f"lock held by {current_holder}, not {holder}")
write_lock_meta(task_id, holder, args.ttl)
print(f"renewed: {task_id} (ttl={args.ttl}s)")
def _deterministic_token(task: dict[str, Any], number: int, salt: str = "") -> str:
"""A stable token derived from immutable task data, so migration is idempotent.
Re-running migrate on an already-migrated task produces the SAME id (no churn). Uses
created_at for the time-sortable head, and a content hash for the random tail.
"""
created = task.get("created_at", "")
try:
ms = int(parse_iso(created).timestamp() * 1000) if created else 0
except ValueError:
ms = 0
time_part = _base36(ms, 4)[-4:] if ms else "0000"
seed = f"{number}|{created}|{task.get('title', '')}|{normalize_slug(task.get('id', ''))}|{salt}"
digest = hashlib.sha256(seed.encode("utf-8")).hexdigest()
tail = _base36(int(digest[:12], 16), TOKEN_LEN - 4)[: TOKEN_LEN - 4]
return _force_leading_digit(time_part + tail)
def cmd_migrate(args: argparse.Namespace) -> None:
"""Migrate every task to the collision-free ``NNNN-TOKEN-slug`` scheme.
Idempotent and re-runnable: a task already in the new scheme is left untouched (its id
is stable). Legacy ``NNNN-slug`` ids (including duplicate-prefix collisions) get a
deterministic token appended, which makes colliding tasks distinct WITHOUT changing
their human-facing number. Filenames, the ``id`` field, and lock dirs are all moved
together; task data/status/history are preserved.
"""
with global_mutex():
entries: list[tuple[Path, dict[str, Any]]] = []
for path in sorted(TASKS_DIR.glob("*.json")):
entries.append((path, json.loads(path.read_text(encoding="utf-8"))))
if not entries:
print("no tasks to migrate")
return
# Migrate oldest-first so any never-numbered legacy tasks get sensible numbers.
entries.sort(key=lambda item: (item[1].get("created_at", ""), item[1].get("id", "")))
next_number = max_existing_number() + 1
migrated = 0
used_ids: set[str] = set()
for path, task in entries:
old_id = task["id"]
full = ID_FULL_RE.match(old_id)
if full:
# Already new-scheme; keep as-is.
used_ids.add(old_id)
continue
legacy = ID_LEGACY_RE.match(old_id)
if legacy:
number = int(legacy.group(1))
slug = normalize_slug(old_id)
else:
number = next_number
next_number += 1
slug = normalize_slug(old_id)
token = _deterministic_token(task, number)
new_id = make_task_id(number, token, slug)
# Guard against the vanishingly-rare token clash within this migration.
attempt = 0
while new_id in used_ids or (task_path(new_id).exists() and new_id != old_id):
attempt += 1
token = _deterministic_token(task, number, salt=str(attempt))
new_id = make_task_id(number, token, slug)
used_ids.add(new_id)
task["id"] = new_id
task["updated_at"] = now_iso()
old_lock = lock_dir(old_id)
new_lock = lock_dir(new_id)
if old_lock.is_dir() and old_lock != new_lock:
if new_lock.exists():
shutil.rmtree(new_lock, ignore_errors=True)
old_lock.rename(new_lock)
meta = read_lock_meta(new_id)
if meta is not None:
meta["task_id"] = new_id
lock_meta_path(new_id).write_text(
json.dumps(meta, indent=2) + "\n",
encoding="utf-8",
)
new_path = task_path(new_id)
new_path.write_text(json.dumps(task, indent=2) + "\n", encoding="utf-8")
if path != new_path:
path.unlink(missing_ok=True)
print(f"migrated: {old_id} -> {new_id}")
migrated += 1
write_counter(max(next_number, max_existing_number() + 1, read_counter()))
if migrated:
print(f"migrated {migrated} task(s); next number hint = {read_counter():0{ID_WIDTH}d}")
else:
print("all tasks already use the collision-free id scheme")
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="task",
description="File-backed task manager with collision-free ids and agent locks.",
)
sub = parser.add_subparsers(dest="command", required=True)
create = sub.add_parser("create", help="Create a task")
create.add_argument("--title", required=True)
create.add_argument("--description", default="")
create.add_argument("--id", default="")
create.add_argument("--status", default="open", choices=sorted(STATUSES))
create.add_argument("--effort", default="default", choices=sorted(EFFORTS),
help="Complexity hint: default=sonnet, high=opus, extreme=fable")
create.add_argument("--priority", default="medium", choices=sorted(PRIORITIES),
help="Scheduling priority: high tasks are picked up first")
create.set_defaults(func=cmd_create)
list_cmd = sub.add_parser("list", help="List tasks")
list_cmd.add_argument("--status")
list_cmd.add_argument("--priority", choices=sorted(PRIORITIES))
list_cmd.add_argument("--effort", choices=sorted(EFFORTS))
list_cmd.add_argument("--json", action="store_true")
list_cmd.set_defaults(func=cmd_list)
show = sub.add_parser("show", help="Show one task")
show.add_argument("id")
show.add_argument("--json", action="store_true")
show.set_defaults(func=cmd_show)
update = sub.add_parser("update", help="Update task fields")
update.add_argument("id")
update.add_argument("--title")
update.add_argument("--description")
update.add_argument("--status", choices=sorted(STATUSES))
update.add_argument("--effort", choices=sorted(EFFORTS))
update.add_argument("--priority", choices=sorted(PRIORITIES))
update.set_defaults(func=cmd_update)
delete = sub.add_parser("delete", help="Delete a task")
delete.add_argument("id")
delete.add_argument("--force", action="store_true")
delete.set_defaults(func=cmd_delete)
acquire = sub.add_parser("acquire", help="Acquire task lock (required before working)")
acquire.add_argument("id")
acquire.add_argument("--holder")
acquire.add_argument("--ttl", type=int, default=DEFAULT_TTL)
acquire.set_defaults(func=cmd_acquire)
release = sub.add_parser("release", help="Release task lock")
release.add_argument("id")
release.add_argument("--holder")
release.add_argument("--force", action="store_true")
release.set_defaults(func=cmd_release)
renew = sub.add_parser("renew", help="Extend lock TTL")
renew.add_argument("id")
renew.add_argument("--holder")
renew.add_argument("--ttl", type=int, default=DEFAULT_TTL)
renew.set_defaults(func=cmd_renew)
migrate = sub.add_parser(
"migrate",
help="Migrate all task files to the collision-free NNNN-TOKEN-slug id scheme",
)
migrate.set_defaults(func=cmd_migrate)
return parser
def main() -> None:
args = build_parser().parse_args()
args.func(args)
if __name__ == "__main__":
main()