mini-trellis 0.2.1 → 0.2.2

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 (30) hide show
  1. package/README.md +30 -2
  2. package/dist/commands/doctor.d.ts.map +1 -1
  3. package/dist/commands/doctor.js +10 -2
  4. package/dist/commands/doctor.js.map +1 -1
  5. package/dist/commands/migrate.d.ts +8 -0
  6. package/dist/commands/migrate.d.ts.map +1 -1
  7. package/dist/commands/migrate.js +123 -4
  8. package/dist/commands/migrate.js.map +1 -1
  9. package/dist/commands/refresh.d.ts +1 -1
  10. package/dist/commands/refresh.d.ts.map +1 -1
  11. package/dist/commands/refresh.js +19 -1
  12. package/dist/commands/refresh.js.map +1 -1
  13. package/dist/configurators/shared.js +2 -2
  14. package/dist/configurators/shared.js.map +1 -1
  15. package/dist/templates/common/commands/remember.md +1 -0
  16. package/dist/templates/common/skills/update-spec.md +1 -0
  17. package/dist/templates/opencode/lib/session-utils.js +8 -8
  18. package/dist/templates/pi/extensions/mini-trellis/index.ts.txt +4 -9
  19. package/dist/templates/shared-hooks/session-start.py +13 -19
  20. package/dist/templates/trellis/scripts/common/config.py +1 -2
  21. package/dist/utils/uninstall-scrubbers.d.ts +8 -0
  22. package/dist/utils/uninstall-scrubbers.d.ts.map +1 -1
  23. package/dist/utils/uninstall-scrubbers.js +66 -18
  24. package/dist/utils/uninstall-scrubbers.js.map +1 -1
  25. package/package.json +2 -2
  26. package/dist/templates/trellis/scripts/common/cli_adapter.py +0 -950
  27. package/dist/templates/trellis/scripts/common/task_context.py +0 -470
  28. package/dist/templates/trellis/scripts/common/task_queue.py +0 -188
  29. package/dist/templates/trellis/scripts/common/task_store.py +0 -1930
  30. package/dist/templates/trellis/scripts/common/task_utils.py +0 -498
@@ -1,1930 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Task CRUD operations.
4
-
5
- Provides:
6
- ensure_tasks_dir - Ensure tasks directory exists
7
- cmd_create - Create a new task
8
- cmd_rename - Rename a task and every reference to it
9
- cmd_archive - Archive completed task
10
- cmd_set_branch - Set git branch for task
11
- cmd_set_base_branch - Set PR target branch
12
- cmd_set_scope - Set scope for PR title
13
- cmd_set_meta - Set/overwrite a task metadata key
14
- cmd_add_subtask - Link child task to parent
15
- cmd_remove_subtask - Unlink child task from parent
16
- """
17
-
18
- from __future__ import annotations
19
-
20
- import argparse
21
- import re
22
- import sys
23
- from dataclasses import dataclass, field
24
- from datetime import datetime
25
- from pathlib import Path
26
-
27
- from .config import (
28
- get_codex_dispatch_mode,
29
- get_packages,
30
- get_session_auto_commit,
31
- is_monorepo,
32
- resolve_package,
33
- validate_package,
34
- )
35
- from .git import (
36
- INDEX_LOCK_RETRY_ATTEMPTS,
37
- branch_exists_locally,
38
- has_git_remote,
39
- index_lock_path,
40
- resolve_default_branch,
41
- run_git,
42
- run_git_retry_index_lock,
43
- stderr_indicates_index_lock,
44
- )
45
- from .io import describe_json_read_failure, read_json_checked, write_json
46
- from .log import Colors, colored
47
- from .paths import (
48
- DEVELOPER_HINT,
49
- DIR_ARCHIVE,
50
- DIR_TASKS,
51
- DIR_WORKFLOW,
52
- FILE_TASK_JSON,
53
- generate_task_date_prefix,
54
- get_developer,
55
- get_repo_root,
56
- get_tasks_dir,
57
- )
58
- from .safe_commit import (
59
- print_gitignore_warning,
60
- safe_archive_paths_to_add,
61
- safe_git_add,
62
- )
63
- from .task_utils import (
64
- archive_destination_for,
65
- archive_task_complete,
66
- find_task_by_name,
67
- is_within_tasks_dir,
68
- resolve_task_dir,
69
- run_task_hooks,
70
- )
71
-
72
-
73
- # =============================================================================
74
- # Helper Functions
75
- # =============================================================================
76
-
77
- # Characters stripped before deciding whether a title / description is empty.
78
- # This is deliberately the *union* of Python's str.strip() default set and
79
- # ECMAScript's String.trim() set, because the two disagree: Python strips
80
- # U+0085 (NEL) and U+001C-U+001F, which JS keeps; JS strips U+FEFF (BOM),
81
- # which Python keeps. Stripping the union means anything create accepts is
82
- # still non-empty after either side trims it, so a record cannot pass here and
83
- # then be refused as empty by a JS pre-archive validator.
84
- BLANK_CHARS = (
85
- "\t\n\v\f\r" # U+0009-U+000D
86
- "\x1c\x1d\x1e\x1f" # U+001C-U+001F separators (Python only)
87
- " " # U+0020 space
88
- "\x85" # U+0085 next line (Python only)
89
- "\xa0" # U+00A0 no-break space
90
- "\u1680" # ogham space mark
91
- "\u2000\u2001\u2002\u2003\u2004\u2005" # en/em quad, en/em/three/four-per-em
92
- "\u2006\u2007\u2008\u2009\u200a" # six-per-em .. hair space
93
- "\u2028\u2029" # line / paragraph separator
94
- "\u202f\u205f\u3000" # narrow nbsp, math space, ideographic space
95
- "\ufeff" # zero-width no-break space / BOM (JS only)
96
- )
97
-
98
-
99
- def strip_blank(value: str | None) -> str:
100
- """Return ``value`` with :data:`BLANK_CHARS` trimmed from both ends."""
101
- return (value or "").strip(BLANK_CHARS)
102
-
103
-
104
- def _slugify(title: str) -> str:
105
- """Convert title to slug (only works with ASCII)."""
106
- result = title.lower()
107
- result = re.sub(r"[^a-z0-9]", "-", result)
108
- result = re.sub(r"-+", "-", result)
109
- result = result.strip("-")
110
- return result
111
-
112
-
113
- def ensure_tasks_dir(repo_root: Path) -> Path:
114
- """Ensure tasks directory exists."""
115
- tasks_dir = get_tasks_dir(repo_root)
116
- archive_dir = tasks_dir / "archive"
117
-
118
- if not tasks_dir.exists():
119
- tasks_dir.mkdir(parents=True)
120
- print(colored(f"Created tasks directory: {tasks_dir}", Colors.GREEN), file=sys.stderr)
121
-
122
- if not archive_dir.exists():
123
- archive_dir.mkdir(parents=True)
124
-
125
- return tasks_dir
126
-
127
-
128
- def _find_archived_task_by_dir_name(tasks_dir: Path, dir_name: str) -> Path | None:
129
- """Find an archived task directory with the exact active-task dir name."""
130
- archive_dir = tasks_dir / DIR_ARCHIVE
131
- if not archive_dir.is_dir():
132
- return None
133
-
134
- for month_dir in sorted(archive_dir.iterdir()):
135
- if not month_dir.is_dir():
136
- continue
137
- candidate = month_dir / dir_name
138
- if candidate.is_dir():
139
- return candidate
140
-
141
- return None
142
-
143
-
144
- def _repo_relative_path(path: Path, repo_root: Path) -> str:
145
- """Format a path relative to the repo root when possible."""
146
- try:
147
- return path.relative_to(repo_root).as_posix()
148
- except ValueError:
149
- return str(path)
150
-
151
-
152
- def _report_read_failure(path: Path, reason: str | None) -> None:
153
- """Print why a JSON file could not be loaded, and what to do about it.
154
-
155
- These commands are about to rewrite the file they just failed to read, so
156
- this message is the last warning the user gets. Exiting non-zero with no
157
- output at all leaves a parse error, a permissions error and an empty file
158
- indistinguishable.
159
- """
160
- problem, hint = describe_json_read_failure(path, reason)
161
- print(colored(f"Error: {problem}", Colors.RED), file=sys.stderr)
162
- print(hint, file=sys.stderr)
163
-
164
-
165
- def _ensure_children_list(data: dict) -> list:
166
- """The task's `children` as a list, repaired in place if it is not one.
167
-
168
- `.get(key, default)` returns the default only when the key is *absent*. A
169
- task.json carrying `"children": null` — older format, or hand-edited —
170
- yields None, and every caller below goes on to use the result as a list.
171
- In `cmd_create` that raise lands *after* the new task.json is written,
172
- leaving a task on disk its parent does not reference.
173
-
174
- The repair is written into `data` rather than only returned, because the
175
- unlink path removes a name it may not find and would otherwise persist the
176
- malformed value untouched — no crash, but the next caller inherits it.
177
-
178
- Anything that is not a list is discarded rather than coerced: a string
179
- would iterate per character and a dict per key, each producing a plausible
180
- child set that is not one.
181
- """
182
- children = data.get("children")
183
- if not isinstance(children, list):
184
- children = []
185
- data["children"] = children
186
- return children
187
-
188
-
189
- def _report_write_failure(path: Path) -> None:
190
- """Print that a JSON write failed. Writes are atomic, so nothing changed."""
191
- print(colored(f"Error: Failed to write {path}", Colors.RED), file=sys.stderr)
192
- print(
193
- "The existing file is unchanged (writes are atomic). "
194
- "Check permissions and free disk space, then retry.",
195
- file=sys.stderr,
196
- )
197
-
198
-
199
- def _restore_child_links(unlinked: dict[Path, str | None]) -> None:
200
- """Put back the parent links this archive attempt already removed.
201
-
202
- The unlink loop below walks a parent's children one at a time, so a
203
- failure part-way through leaves the earlier children carrying
204
- ``parent: null`` while their parent is still in the active tree. That is
205
- the mirror image of the dangling reference the same loop already refuses
206
- to create, and nothing repairs it later either, so undo it before the
207
- failure is reported.
208
-
209
- Restoring is best-effort: if a child cannot be written back, name it so
210
- the caller can re-link it by hand instead of guessing which one broke.
211
- """
212
- broken: list[str] = []
213
- for child_json, original_parent in unlinked.items():
214
- child_data, _ = read_json_checked(child_json)
215
- if child_data is None:
216
- broken.append(child_json.parent.name)
217
- continue
218
- child_data["parent"] = original_parent
219
- if not write_json(child_json, child_data):
220
- broken.append(child_json.parent.name)
221
- if broken:
222
- print(
223
- colored(
224
- f"Warning: could not restore the parent link on: {', '.join(broken)}. "
225
- "Re-link each one with `python3 .trellis/scripts/task.py "
226
- "add-subtask <parent> <child>`.",
227
- Colors.RED,
228
- ),
229
- file=sys.stderr,
230
- )
231
-
232
-
233
- # =============================================================================
234
- # Sub-agent platform detection + JSONL context files
235
- # =============================================================================
236
-
237
- # Config directories of platforms that consume implement.jsonl / check.jsonl.
238
- # Keep in sync with src/types/ai-tools.ts AI_TOOLS entries — these are the
239
- # platforms listed in workflow.md's "agent-capable" Skill Routing block.
240
- # Codex is checked separately because explicit inline mode does not consume
241
- # JSONL. Kilo / Antigravity / Devin are NOT in this list either: they load
242
- # specs through skills instead of JSONL.
243
- _SUBAGENT_CONFIG_DIRS: tuple[str, ...] = (
244
- ".claude",
245
- ".cursor",
246
- ".kiro",
247
- ".gemini",
248
- ".opencode",
249
- ".qoder",
250
- ".codebuddy",
251
- ".factory", # Factory Droid
252
- ".github/copilot",
253
- ".pi", # Pi Agent
254
- ".trae", # Trae IDE
255
- ".omp", # Oh My Pi
256
- ".zcode", # ZCode
257
- ".grok", # Grok Build
258
- ".kimi-code", # Kimi Code
259
- )
260
- _CODEX_CONFIG_DIR = ".codex"
261
-
262
-
263
- def _has_subagent_platform(repo_root: Path) -> bool:
264
- """Return True if any sub-agent-capable platform is configured.
265
-
266
- Detected by probing well-known config directories at the repo root. Codex
267
- counts by default through ``codex.dispatch_mode: auto`` (including the
268
- legacy ``sub-agent`` alias); explicit inline mode loads context through
269
- skills, not JSONL.
270
- """
271
- for config_dir in _SUBAGENT_CONFIG_DIRS:
272
- if (repo_root / config_dir).is_dir():
273
- return True
274
- if (repo_root / _CODEX_CONFIG_DIR).is_dir():
275
- return get_codex_dispatch_mode(repo_root) == "auto"
276
- return False
277
-
278
-
279
- def _parse_meta_pairs(pairs: list[str] | None) -> dict[str, str] | None:
280
- """Parse repeatable ``--meta key=value`` pairs into a dict.
281
-
282
- Returns ``None`` (after printing an error naming the bad value) on the
283
- first malformed pair: missing ``=`` or an empty key. Values are stored
284
- as-is (strings, no nesting, no type coercion).
285
- """
286
- meta: dict[str, str] = {}
287
- for pair in pairs or []:
288
- key, sep, value = pair.partition("=")
289
- if not sep or not key:
290
- print(
291
- colored(f"Error: malformed --meta value '{pair}' (expected key=value)", Colors.RED),
292
- file=sys.stderr,
293
- )
294
- return None
295
- meta[key] = value
296
- return meta
297
-
298
-
299
- def _default_prd_content(title: str, description: str | None = None) -> str:
300
- """Return the default PRD skeleton created with every task."""
301
- goal = (description or "").strip() or "TBD."
302
- heading = title.strip() or "Untitled task"
303
- return f"""# {heading}
304
-
305
- ## Goal
306
-
307
- {goal}
308
-
309
- ## Requirements
310
-
311
- - TBD
312
-
313
- ## Acceptance Criteria
314
-
315
- - [ ] TBD
316
-
317
- ## Notes
318
-
319
- - Keep `prd.md` focused on requirements, constraints, and acceptance criteria.
320
- - Lightweight tasks can remain PRD-only.
321
- - For complex tasks, add `design.md` for technical design and `implement.md` for execution planning before `task.py start`.
322
- """
323
-
324
-
325
- # =============================================================================
326
- # Command: create
327
- # =============================================================================
328
-
329
- def cmd_create(args: argparse.Namespace) -> int:
330
- """Create a new task."""
331
- repo_root = get_repo_root()
332
-
333
- # Title and description are checked first, before ensure_tasks_dir and any
334
- # other write, so a rejected create leaves the tree untouched. Both are
335
- # required non-empty by pre-archive validation; catching that here costs
336
- # one retyped command instead of blocking a PR hours later.
337
- if not strip_blank(args.title):
338
- print(colored("Error: title is required", Colors.RED), file=sys.stderr)
339
- print(
340
- 'Pass a non-empty <title> (whitespace only does not count): a task '
341
- "with an empty title is refused at archive.",
342
- file=sys.stderr,
343
- )
344
- return 1
345
-
346
- description = strip_blank(getattr(args, "description", None))
347
- if not description:
348
- print(colored("Error: --description is required", Colors.RED), file=sys.stderr)
349
- print(
350
- 'Pass --description "<what this task delivers>" (whitespace only does '
351
- "not count): a task with an empty description is refused at archive.",
352
- file=sys.stderr,
353
- )
354
- return 1
355
-
356
- # Validate --meta (CLI source: fail-fast, before any directory is created)
357
- meta = _parse_meta_pairs(getattr(args, "meta", None))
358
- if meta is None:
359
- return 1
360
-
361
- # Validate --package (CLI source: fail-fast)
362
- package: str | None = getattr(args, "package", None)
363
- if not is_monorepo(repo_root):
364
- # Single-repo: ignore --package, no package prefix
365
- if package:
366
- print(colored(f"Warning: --package ignored in single-repo project", Colors.YELLOW), file=sys.stderr)
367
- package = None
368
- elif package:
369
- if not validate_package(package, repo_root):
370
- packages = get_packages(repo_root)
371
- available = ", ".join(sorted(packages.keys())) if packages else "(none)"
372
- print(colored(f"Error: unknown package '{package}'. Available: {available}", Colors.RED), file=sys.stderr)
373
- return 1
374
- else:
375
- # Inferred: default_package → None (no task.json yet for create)
376
- package = resolve_package(repo_root=repo_root)
377
-
378
- # Default assignee to current developer
379
- assignee = args.assignee
380
- if not assignee:
381
- assignee = get_developer(repo_root)
382
- if not assignee:
383
- print(colored("Error: No developer set. Run init_developer.py first or use --assignee", Colors.RED), file=sys.stderr)
384
- print(DEVELOPER_HINT, file=sys.stderr)
385
- return 1
386
-
387
- ensure_tasks_dir(repo_root)
388
-
389
- # Get current developer as creator
390
- creator = get_developer(repo_root) or assignee
391
-
392
- # Generate slug if not provided. A title-derived slug is sanitized by
393
- # _slugify; an explicit --slug is not, so reject the characters that would
394
- # let it escape the tasks directory once joined into the dir name.
395
- slug = args.slug or _slugify(args.title)
396
- if not slug:
397
- print(colored("Error: could not generate slug from title", Colors.RED), file=sys.stderr)
398
- return 1
399
-
400
- if args.slug and ("/" in slug or "\\" in slug or ".." in slug):
401
- print(
402
- colored(
403
- f"Error: --slug must be a plain name without path separators or '..': {slug}",
404
- Colors.RED,
405
- ),
406
- file=sys.stderr,
407
- )
408
- return 1
409
-
410
- # Create task directory with MM-DD-slug format
411
- tasks_dir = get_tasks_dir(repo_root)
412
- date_prefix = generate_task_date_prefix()
413
-
414
- # Guard against date-prefixed --slug (e.g. a full task dir name pasted in),
415
- # which would otherwise produce MM-DD-MM-DD-slug (issue #377). Only an
416
- # explicit --slug is guarded; title-derived slugs are left untouched.
417
- if args.slug:
418
- m = re.match(r"^(\d{2})-(\d{2})-(.+)$", slug)
419
- if m and 1 <= int(m.group(1)) <= 12 and 1 <= int(m.group(2)) <= 31:
420
- slug_prefix = f"{m.group(1)}-{m.group(2)}"
421
- if slug_prefix == date_prefix:
422
- slug = m.group(3)
423
- print(
424
- colored(
425
- f'warning: --slug should not include the MM-DD prefix; normalized to "{slug}"',
426
- Colors.YELLOW,
427
- ),
428
- file=sys.stderr,
429
- )
430
- else:
431
- print(
432
- colored(
433
- f"Error: --slug starts with a date prefix ({slug_prefix}-), but task.py create always uses today's date ({date_prefix}).",
434
- Colors.RED,
435
- ),
436
- file=sys.stderr,
437
- )
438
- print(f"Pass only the slug body, e.g. --slug {m.group(3)}", file=sys.stderr)
439
- return 1
440
-
441
- # Resolve --parent before anything is created. An explicit --parent that
442
- # cannot be linked is a failed request, not a warning: creating the task
443
- # anyway leaves a half-specified relationship that reads as success.
444
- parent_dir: Path | None = None
445
- parent_data: dict | None = None
446
- if args.parent:
447
- parent_dir = resolve_task_dir(args.parent, repo_root)
448
- if parent_dir is None:
449
- print(colored(f"Error: Parent task not resolved: {args.parent}", Colors.RED), file=sys.stderr)
450
- print("No task was created. Pass an existing task directory to --parent.", file=sys.stderr)
451
- return 1
452
- parent_json_path = parent_dir / FILE_TASK_JSON
453
- if not parent_json_path.is_file():
454
- print(colored(f"Error: Parent task.json not found: {args.parent}", Colors.RED), file=sys.stderr)
455
- print("No task was created. Pass an existing task directory to --parent.", file=sys.stderr)
456
- return 1
457
- parent_data, parent_reason = read_json_checked(parent_json_path)
458
- if parent_data is None:
459
- _report_read_failure(parent_json_path, parent_reason)
460
- print("No task was created. Fix the parent task.json, then retry.", file=sys.stderr)
461
- return 1
462
-
463
- dir_name = f"{date_prefix}-{slug}"
464
- task_dir = tasks_dir / dir_name
465
- task_json_path = task_dir / FILE_TASK_JSON
466
-
467
- archived_task_dir = _find_archived_task_by_dir_name(tasks_dir, dir_name)
468
- if archived_task_dir:
469
- print(colored(f"Error: Task already archived: {dir_name}", Colors.RED), file=sys.stderr)
470
- print(f"Archived at: {_repo_relative_path(archived_task_dir, repo_root)}", file=sys.stderr)
471
- print("Use a new slug if you intend to create a new task.", file=sys.stderr)
472
- return 1
473
-
474
- # Reusing a slug on the same day is an ordinary accident, and continuing
475
- # would rewrite the existing task.json below — resetting status, children,
476
- # parent, branch and meta, which nothing else can reconstruct. Fail like
477
- # the archived-name collision above unless the caller asks for it.
478
- if task_dir.exists():
479
- if not getattr(args, "force", False):
480
- print(colored(f"Error: Task already exists: {dir_name}", Colors.RED), file=sys.stderr)
481
- print(f"Existing task at: {_repo_relative_path(task_dir, repo_root)}", file=sys.stderr)
482
- print(
483
- "Use a different --slug, or pass --force to overwrite its task.json.",
484
- file=sys.stderr,
485
- )
486
- return 1
487
- print(
488
- colored(
489
- f"Warning: --force: overwriting task.json in existing task: {dir_name}",
490
- Colors.YELLOW,
491
- ),
492
- file=sys.stderr,
493
- )
494
- created_dir = False
495
- else:
496
- task_dir.mkdir(parents=True)
497
- created_dir = True
498
-
499
- today = datetime.now().strftime("%Y-%m-%d")
500
-
501
- # Record the PR target branch. Prefer the repo's actual default branch
502
- # (origin/HEAD) so creating a task from a feature branch doesn't
503
- # mis-stamp that feature branch as the PR target (#399 item 1). Falls
504
- # back to the checked-out branch when the default can't be resolved
505
- # (no remote configured, offline, etc.) — the pre-existing behavior.
506
- # --base-branch lets the caller override both when neither is correct.
507
- _, branch_out, _ = run_git(["branch", "--show-current"], cwd=repo_root)
508
- current_branch = branch_out.strip() or "main"
509
- explicit_base_branch: str | None = getattr(args, "base_branch", None)
510
- if explicit_base_branch:
511
- base_branch = explicit_base_branch
512
- else:
513
- resolved_base_branch = resolve_default_branch(repo_root)
514
- if resolved_base_branch:
515
- base_branch = resolved_base_branch
516
- else:
517
- base_branch = current_branch
518
- print(
519
- colored(
520
- f"warning: could not resolve the repository's default branch "
521
- f"(no remote configured, offline, etc.); stamping base_branch as "
522
- f"the checked-out branch '{base_branch}'. Pass --base-branch to override.",
523
- Colors.YELLOW,
524
- ),
525
- file=sys.stderr,
526
- )
527
-
528
- task_data = {
529
- "id": slug,
530
- "name": slug,
531
- "title": args.title,
532
- "description": description,
533
- "status": "planning",
534
- "dev_type": None,
535
- "scope": None,
536
- "package": package,
537
- "priority": args.priority,
538
- "creator": creator,
539
- "assignee": assignee,
540
- "createdAt": today,
541
- "completedAt": None,
542
- "branch": None,
543
- "base_branch": base_branch,
544
- "worktree_path": None,
545
- "commit": None,
546
- "pr_url": None,
547
- "subtasks": [],
548
- "children": [],
549
- "parent": None,
550
- "relatedFiles": [],
551
- "notes": "",
552
- "meta": meta,
553
- }
554
-
555
- # A directory without task.json is not a task: `list` hides it and every
556
- # lifecycle command refuses it. Fail here rather than printing "Created
557
- # task" and emitting the path for script chaining.
558
- if not write_json(task_json_path, task_data):
559
- _report_write_failure(task_json_path)
560
- print(colored(f"No task was created: {dir_name}", Colors.RED), file=sys.stderr)
561
- if created_dir:
562
- try:
563
- task_dir.rmdir()
564
- except OSError:
565
- print(
566
- f"Leftover empty directory: {_repo_relative_path(task_dir, repo_root)}",
567
- file=sys.stderr,
568
- )
569
- return 1
570
-
571
- prd_path = task_dir / "prd.md"
572
- if not prd_path.exists():
573
- prd_path.write_text(
574
- _default_prd_content(args.title, description),
575
- encoding="utf-8",
576
- )
577
-
578
- # Create empty implement.jsonl / check.jsonl for sub-agent-capable
579
- # platforms. They stay empty until the agent curates real entries during
580
- # planning — a placeholder row would read as unresolved scaffolding to
581
- # `task.py validate` and to PR preflight, so the curation instructions go
582
- # to the console below instead of into the files. Agent-less platforms
583
- # (Kilo / Antigravity / Devin) skip this — they load specs via the
584
- # trellis-before-dev skill instead of JSONL.
585
- created_jsonl = False
586
- if _has_subagent_platform(repo_root):
587
- for jsonl_name in ("implement.jsonl", "check.jsonl"):
588
- jsonl_path = task_dir / jsonl_name
589
- if not jsonl_path.exists():
590
- jsonl_path.write_text("", encoding="utf-8")
591
- created_jsonl = True
592
-
593
- # Establish the bidirectional link. Both sides were validated above, so a
594
- # failure here is a write failure, not a bad argument.
595
- if parent_dir is not None and parent_data is not None:
596
- parent_json_path = parent_dir / FILE_TASK_JSON
597
-
598
- # Add child to parent's children list
599
- parent_children = _ensure_children_list(parent_data)
600
- if dir_name not in parent_children:
601
- parent_children.append(dir_name)
602
- parent_data["children"] = parent_children
603
- if not write_json(parent_json_path, parent_data):
604
- _report_write_failure(parent_json_path)
605
- print(
606
- f"The task exists at {_repo_relative_path(task_dir, repo_root)} but is NOT "
607
- f"linked to {parent_dir.name}. Re-link with: task.py add-subtask "
608
- f"{parent_dir.name} {dir_name}",
609
- file=sys.stderr,
610
- )
611
- return 1
612
-
613
- # Set parent in child's task.json
614
- task_data["parent"] = parent_dir.name
615
- if not write_json(task_json_path, task_data):
616
- _report_write_failure(task_json_path)
617
- print(
618
- f"Link is half-written: {parent_dir.name} now lists '{dir_name}' as a child, "
619
- f"but the new task does not record its parent.",
620
- file=sys.stderr,
621
- )
622
- return 1
623
-
624
- print(colored(f"Linked as child of: {parent_dir.name}", Colors.GREEN), file=sys.stderr)
625
-
626
- # Auto-activate the new task so the per-turn breadcrumb fires planning
627
- # state. Best-effort: gracefully degrade if no session identity (CLI run
628
- # outside an AI session) — the task is still created, the user can run
629
- # task.py start later. Pointer is session-scoped so this never affects
630
- # other AI sessions.
631
- if getattr(args, "no_start", False):
632
- print(
633
- colored(
634
- "Skipped session activation (--no-start); run task.py start when ready.",
635
- Colors.YELLOW,
636
- ),
637
- file=sys.stderr,
638
- )
639
- else:
640
- try:
641
- from .active_task import resolve_context_key, set_active_task
642
- except Exception as exc:
643
- print(
644
- colored(f"Warning: session activation unavailable (import failed: {exc})", Colors.YELLOW),
645
- file=sys.stderr,
646
- )
647
- else:
648
- try:
649
- context_key = resolve_context_key()
650
- except Exception as exc:
651
- print(
652
- colored(f"Warning: session activation failed (context resolution: {exc})", Colors.YELLOW),
653
- file=sys.stderr,
654
- )
655
- else:
656
- # No session identity is the normal CLI-outside-an-AI-session
657
- # case (see comment above) — stay silent, not a failure.
658
- if context_key:
659
- try:
660
- rel_dir = task_dir.relative_to(repo_root).as_posix()
661
- except ValueError:
662
- rel_dir = str(task_dir)
663
- try:
664
- active = set_active_task(rel_dir, repo_root)
665
- except Exception as exc:
666
- print(
667
- colored(f"Warning: session activation failed (pointer persistence: {exc})", Colors.YELLOW),
668
- file=sys.stderr,
669
- )
670
- else:
671
- if active:
672
- print(
673
- colored(f"Activated task for this session: {active.task_path}", Colors.GREEN),
674
- file=sys.stderr,
675
- )
676
- print(f"Source: {active.source}", file=sys.stderr)
677
- else:
678
- print(
679
- colored("Warning: session activation failed (no pointer returned)", Colors.YELLOW),
680
- file=sys.stderr,
681
- )
682
-
683
- print(colored(f"Created task: {dir_name}", Colors.GREEN), file=sys.stderr)
684
- print("", file=sys.stderr)
685
- print(colored("Next steps:", Colors.BLUE), file=sys.stderr)
686
- print(" - Fill prd.md with requirements and acceptance criteria", file=sys.stderr)
687
- print(" - Lightweight task: PRD-only is valid", file=sys.stderr)
688
- print(" - Complex task: add design.md and implement.md before task.py start", file=sys.stderr)
689
- if created_jsonl:
690
- print(
691
- " - Curate implement.jsonl / check.jsonl (created empty) as spec/research "
692
- "manifests before task.py start when sub-agents need context:",
693
- file=sys.stderr,
694
- )
695
- print(
696
- ' one JSON object per line — {"file": "<path>", "reason": "<why>"}; '
697
- "spec/research docs only, no code paths",
698
- file=sys.stderr,
699
- )
700
- print(
701
- " list available specs: python3 .trellis/scripts/get_context.py --mode packages",
702
- file=sys.stderr,
703
- )
704
- print(" - Use /trellis:continue or phase context to decide the next step", file=sys.stderr)
705
- print("", file=sys.stderr)
706
-
707
- # Output relative path for script chaining
708
- print(f"{DIR_WORKFLOW}/{DIR_TASKS}/{dir_name}")
709
-
710
- run_task_hooks("after_create", task_json_path, repo_root)
711
- return 0
712
-
713
-
714
- # =============================================================================
715
- # Command: rename
716
- # =============================================================================
717
-
718
- # task.json fields that carry the task's own slug. The directory name carries
719
- # it too, prefixed with the creation date; everything else that names the task
720
- # (parent / children / subtasks in *other* tasks, jsonl paths) stores the full
721
- # directory name instead.
722
- RENAME_IDENTITY_FIELDS: tuple[str, ...] = ("id", "name")
723
-
724
- _JSONL_NAMES: tuple[str, ...] = ("implement.jsonl", "check.jsonl")
725
-
726
-
727
- @dataclass
728
- class _RenamePlan:
729
- """Every change a rename would make, computed before anything is written.
730
-
731
- ``--dry-run`` and the real run render their output from this one structure,
732
- so the printed change set cannot drift from the applied one.
733
- """
734
-
735
- task_dir: Path
736
- new_dir: Path
737
- old_name: str
738
- new_name: str
739
- old_rel: str
740
- new_rel: str
741
- task_json_path: Path
742
- task_data: dict
743
- # (field, current value, new value) for each identity field that changes.
744
- identity: list[tuple[str, object, str]] = field(default_factory=list)
745
- # (jsonl path, changed line numbers, full new file text)
746
- jsonl: list[tuple[Path, list[int], str]] = field(default_factory=list)
747
- # (other task's task.json, rewritten data, labels of the changed refs)
748
- backrefs: list[tuple[Path, dict, list[str]]] = field(default_factory=list)
749
- # (file, line number) of old-name mentions elsewhere under .trellis/
750
- reported: list[tuple[Path, int]] = field(default_factory=list)
751
- # Task dirs whose task.json could not be read, so back-refs in them are
752
- # neither rewritten nor ruled out.
753
- unreadable: list[Path] = field(default_factory=list)
754
-
755
-
756
- def _split_date_prefix(dir_name: str) -> tuple[str, str]:
757
- """Split ``MM-DD-slug`` into ``("MM-DD", "slug")``.
758
-
759
- Returns ``("", dir_name)`` when there is no plausible date prefix, so a
760
- hand-made directory name without one is renamed to the bare slug.
761
- """
762
- m = re.match(r"^(\d{2})-(\d{2})-(.+)$", dir_name)
763
- if m and 1 <= int(m.group(1)) <= 12 and 1 <= int(m.group(2)) <= 31:
764
- return f"{m.group(1)}-{m.group(2)}", m.group(3)
765
- return "", dir_name
766
-
767
-
768
- def _validate_rename_slug(slug: str, date_prefix: str) -> str | None:
769
- """Return the slug body to rename to, or None after reporting the refusal.
770
-
771
- Mirrors ``create``'s ``--slug`` handling: no path separators or ``..`` (the
772
- slug is joined into a directory name), and a pasted-in date prefix is
773
- normalized away rather than doubled — but a rename keeps the task's
774
- *original* creation date, not today's.
775
- """
776
- if not slug:
777
- print(colored("Error: new slug is required", Colors.RED), file=sys.stderr)
778
- return None
779
-
780
- if "/" in slug or "\\" in slug or ".." in slug:
781
- print(
782
- colored(
783
- f"Error: <new-slug> must be a plain name without path separators or '..': {slug}",
784
- Colors.RED,
785
- ),
786
- file=sys.stderr,
787
- )
788
- return None
789
-
790
- slug_prefix, body = _split_date_prefix(slug)
791
- if not slug_prefix:
792
- return slug
793
- if slug_prefix == date_prefix:
794
- print(
795
- colored(
796
- f'warning: <new-slug> should not include the MM-DD prefix; normalized to "{body}"',
797
- Colors.YELLOW,
798
- ),
799
- file=sys.stderr,
800
- )
801
- return body
802
- print(
803
- colored(
804
- f"Error: <new-slug> starts with a date prefix ({slug_prefix}-), but rename keeps "
805
- f"the task's own creation date ({date_prefix}).",
806
- Colors.RED,
807
- ),
808
- file=sys.stderr,
809
- )
810
- print(f"Pass only the slug body, e.g. {body}", file=sys.stderr)
811
- return None
812
-
813
-
814
- def _plan_jsonl_rewrites(
815
- task_dir: Path, old_rel: str, new_rel: str
816
- ) -> list[tuple[Path, list[int], str]]:
817
- """Plan rewrites of context entries pointing under the old task directory.
818
-
819
- Matching on ``<old path>/`` rather than the bare path keeps a sibling task
820
- whose name merely starts with this one's out of the rewrite.
821
- """
822
- rewrites: list[tuple[Path, list[int], str]] = []
823
- needle = f"{old_rel}/"
824
- replacement = f"{new_rel}/"
825
-
826
- for jsonl_name in _JSONL_NAMES:
827
- jsonl_path = task_dir / jsonl_name
828
- if not jsonl_path.is_file():
829
- continue
830
- try:
831
- lines = jsonl_path.read_text(encoding="utf-8").splitlines(keepends=True)
832
- except (OSError, UnicodeDecodeError):
833
- continue
834
-
835
- changed: list[int] = []
836
- for index, line in enumerate(lines):
837
- if needle in line:
838
- lines[index] = line.replace(needle, replacement)
839
- changed.append(index + 1)
840
- if changed:
841
- rewrites.append((jsonl_path, changed, "".join(lines)))
842
-
843
- return rewrites
844
-
845
-
846
- def _plan_backrefs(
847
- tasks_dir: Path, task_dir: Path, old_name: str, new_name: str
848
- ) -> tuple[list[tuple[Path, dict, list[str]]], list[Path]]:
849
- """Plan back-reference rewrites in the other active tasks.
850
-
851
- Returns ``(changes, unreadable)``. ``subtasks`` is the legacy spelling of
852
- ``children`` and is still carried in older task.json files, so both lists
853
- are rewritten.
854
- """
855
- changes: list[tuple[Path, dict, list[str]]] = []
856
- unreadable: list[Path] = []
857
-
858
- for candidate in sorted(tasks_dir.iterdir()):
859
- if not candidate.is_dir() or candidate.name == DIR_ARCHIVE:
860
- continue
861
- if candidate == task_dir:
862
- continue
863
- json_path = candidate / FILE_TASK_JSON
864
- if not json_path.is_file():
865
- continue
866
-
867
- data, _reason = read_json_checked(json_path)
868
- if data is None:
869
- unreadable.append(json_path)
870
- continue
871
-
872
- labels: list[str] = []
873
- if data.get("parent") == old_name:
874
- data["parent"] = new_name
875
- labels.append("parent")
876
- for list_field in ("children", "subtasks"):
877
- values = data.get(list_field)
878
- if not isinstance(values, list):
879
- continue
880
- for index, value in enumerate(values):
881
- if value == old_name:
882
- values[index] = new_name
883
- labels.append(f"{list_field}[{index}]")
884
-
885
- if labels:
886
- changes.append((json_path, data, labels))
887
-
888
- return changes, unreadable
889
-
890
-
891
- def _plan_reported_refs(
892
- repo_root: Path, task_dir: Path, rewritten: set[Path], old_name: str
893
- ) -> list[tuple[Path, int]]:
894
- """Find remaining mentions of the old task name elsewhere under .trellis/.
895
-
896
- These are reported, never rewritten: journal entries and workflow prose
897
- cite tasks in free text, and a blind substitution there is how a rename
898
- turns into a diff nobody asked for. The boundary-anchored pattern keeps a
899
- longer task name that merely contains this one out.
900
-
901
- Runtime session pointers are excluded because they are not prose and they
902
- *are* rewritten — see ``repoint_task_in_sessions``. Listing them here as
903
- "not rewritten" would be a false statement about the one file whose
904
- staleness actually breaks the next command.
905
- """
906
- from .active_task import _runtime_sessions_dir
907
-
908
- pattern = re.compile(
909
- r"(?<![0-9A-Za-z_-])" + re.escape(old_name) + r"(?![0-9A-Za-z_-])"
910
- )
911
- hits: list[tuple[Path, int]] = []
912
- trellis_dir = repo_root / DIR_WORKFLOW
913
- sessions_dir = _runtime_sessions_dir(repo_root)
914
- if not trellis_dir.is_dir():
915
- return hits
916
-
917
- for path in sorted(trellis_dir.rglob("*")):
918
- if not path.is_file() or path in rewritten:
919
- continue
920
- if path == task_dir or task_dir in path.parents:
921
- continue
922
- if path.parent == sessions_dir:
923
- continue
924
- if any(
925
- part == "__pycache__" or part.startswith(".backup-")
926
- for part in path.relative_to(trellis_dir).parts[:-1]
927
- ):
928
- continue
929
- try:
930
- text = path.read_text(encoding="utf-8")
931
- except (OSError, UnicodeDecodeError):
932
- continue
933
- for lineno, line in enumerate(text.splitlines(), 1):
934
- if pattern.search(line):
935
- hits.append((path, lineno))
936
-
937
- return hits
938
-
939
-
940
- def _render_rename_plan(plan: _RenamePlan, repo_root: Path) -> list[str]:
941
- """Render the change set. Identical for --dry-run and the real run."""
942
- lines = [
943
- f"rename: {plan.old_name} -> {plan.new_name}",
944
- f" dir: {plan.old_rel} -> {plan.new_rel}",
945
- ]
946
- for field_name, old_value, new_value in plan.identity:
947
- lines.append(f" task.json: {field_name}: {old_value} -> {new_value}")
948
- for json_path, _data, labels in plan.backrefs:
949
- rel = _repo_relative_path(json_path, repo_root)
950
- for label in labels:
951
- lines.append(
952
- f" backref: {rel}: {label}: {plan.old_name} -> {plan.new_name}"
953
- )
954
- for jsonl_path, linenos, _text in plan.jsonl:
955
- rel = _repo_relative_path(jsonl_path, repo_root)
956
- for lineno in linenos:
957
- lines.append(
958
- f" jsonl: {rel}:{lineno}: {plan.old_rel}/ -> {plan.new_rel}/"
959
- )
960
- for path, lineno in plan.reported:
961
- lines.append(
962
- f" reported (not rewritten): {_repo_relative_path(path, repo_root)}:{lineno}"
963
- )
964
- lines.append(
965
- f" sessions: any active-task pointer at {plan.old_rel} is repointed to {plan.new_rel}"
966
- )
967
- return lines
968
-
969
-
970
- def _rename_interrupted(plan: _RenamePlan) -> None:
971
- """Explain how to finish a rename that stopped part-way through."""
972
- print(
973
- f"The task is still at {plan.old_rel} and was NOT moved. Every step up to "
974
- f"this one is idempotent: fix the write failure, then run the same rename "
975
- f"again to finish it.",
976
- file=sys.stderr,
977
- )
978
-
979
-
980
- def _apply_rename(plan: _RenamePlan, repo_root: Path) -> int:
981
- """Write the planned change set.
982
-
983
- The directory move goes last on purpose. Everything before it is an
984
- in-place edit that re-running the identical command recomputes as
985
- already-done, so an interruption leaves a tree that the same command
986
- finishes; a move-first ordering would instead leave the old name
987
- unresolvable and the remaining edits to be made by hand.
988
- """
989
- if plan.identity:
990
- data = dict(plan.task_data)
991
- for field_name, _old_value, new_value in plan.identity:
992
- data[field_name] = new_value
993
- if not write_json(plan.task_json_path, data):
994
- _report_write_failure(plan.task_json_path)
995
- print("Nothing was renamed.", file=sys.stderr)
996
- return 1
997
-
998
- for jsonl_path, _linenos, text in plan.jsonl:
999
- try:
1000
- jsonl_path.write_text(text, encoding="utf-8")
1001
- except OSError as exc:
1002
- print(
1003
- colored(f"Error: Failed to write {jsonl_path}: {exc}", Colors.RED),
1004
- file=sys.stderr,
1005
- )
1006
- _rename_interrupted(plan)
1007
- return 1
1008
-
1009
- for json_path, data, _labels in plan.backrefs:
1010
- if not write_json(json_path, data):
1011
- _report_write_failure(json_path)
1012
- _rename_interrupted(plan)
1013
- return 1
1014
-
1015
- try:
1016
- plan.task_dir.rename(plan.new_dir)
1017
- except OSError as exc:
1018
- print(
1019
- colored(f"Error: Failed to move {plan.old_rel} -> {plan.new_rel}: {exc}", Colors.RED),
1020
- file=sys.stderr,
1021
- )
1022
- _rename_interrupted(plan)
1023
- return 1
1024
-
1025
- # Last, and after the move: a session pointing at the old path would now
1026
- # resolve to a missing directory, so `current` would report the task stale
1027
- # and the context hook would inject nothing until the user ran `start`
1028
- # again. Archive clears these pointers because the task is leaving; rename
1029
- # moves them, because the task is still the one being worked on.
1030
- from .active_task import repoint_task_in_sessions
1031
-
1032
- repoint_task_in_sessions(str(plan.task_dir), str(plan.new_dir), repo_root)
1033
-
1034
- return 0
1035
-
1036
-
1037
- def cmd_rename(args: argparse.Namespace) -> int:
1038
- """Rename a task and every reference to it."""
1039
- repo_root = get_repo_root()
1040
- tasks_dir = get_tasks_dir(repo_root)
1041
-
1042
- task_dir = resolve_task_dir(args.name, repo_root)
1043
- if task_dir is None or not task_dir.is_dir():
1044
- if task_dir is not None:
1045
- print(colored(f"Error: Task not found: {args.name}", Colors.RED), file=sys.stderr)
1046
- return 1
1047
-
1048
- # Narrower than resolve_task_dir's containment: an archived task has left
1049
- # the active set, so its back-references are no longer maintained here.
1050
- if not is_within_tasks_dir(task_dir, repo_root):
1051
- print(
1052
- colored(
1053
- f"Error: refusing to rename '{args.name}': "
1054
- f"{task_dir} is not an active task under {tasks_dir}",
1055
- Colors.RED,
1056
- ),
1057
- file=sys.stderr,
1058
- )
1059
- return 1
1060
-
1061
- old_name = task_dir.name
1062
- date_prefix, _old_slug = _split_date_prefix(old_name)
1063
-
1064
- slug = _validate_rename_slug(args.new_slug, date_prefix)
1065
- if slug is None:
1066
- return 1
1067
-
1068
- new_name = f"{date_prefix}-{slug}" if date_prefix else slug
1069
- if new_name == old_name:
1070
- print(
1071
- colored(f"Error: '{new_name}' is the task's current name", Colors.RED),
1072
- file=sys.stderr,
1073
- )
1074
- return 1
1075
-
1076
- new_dir = task_dir.parent / new_name
1077
- if new_dir.exists():
1078
- print(
1079
- colored(f"Error: Task already exists: {new_name}", Colors.RED),
1080
- file=sys.stderr,
1081
- )
1082
- print(f"Existing task at: {_repo_relative_path(new_dir, repo_root)}", file=sys.stderr)
1083
- print("Pick a different slug.", file=sys.stderr)
1084
- return 1
1085
-
1086
- archived_task_dir = _find_archived_task_by_dir_name(tasks_dir, new_name)
1087
- if archived_task_dir:
1088
- print(
1089
- colored(f"Error: Task already archived: {new_name}", Colors.RED),
1090
- file=sys.stderr,
1091
- )
1092
- print(f"Archived at: {_repo_relative_path(archived_task_dir, repo_root)}", file=sys.stderr)
1093
- print("Pick a different slug.", file=sys.stderr)
1094
- return 1
1095
-
1096
- task_json_path = task_dir / FILE_TASK_JSON
1097
- if not task_json_path.is_file():
1098
- print(
1099
- colored(f"Error: task.json not found at {task_dir}", Colors.RED),
1100
- file=sys.stderr,
1101
- )
1102
- return 1
1103
-
1104
- task_data, reason = read_json_checked(task_json_path)
1105
- if task_data is None:
1106
- _report_read_failure(task_json_path, reason)
1107
- print("Nothing was renamed.", file=sys.stderr)
1108
- return 1
1109
-
1110
- plan = _RenamePlan(
1111
- task_dir=task_dir,
1112
- new_dir=new_dir,
1113
- old_name=old_name,
1114
- new_name=new_name,
1115
- old_rel=_repo_relative_path(task_dir, repo_root),
1116
- new_rel=_repo_relative_path(new_dir, repo_root),
1117
- task_json_path=task_json_path,
1118
- task_data=task_data,
1119
- )
1120
- plan.identity = [
1121
- (name, task_data.get(name), slug)
1122
- for name in RENAME_IDENTITY_FIELDS
1123
- if task_data.get(name) != slug
1124
- ]
1125
- plan.jsonl = _plan_jsonl_rewrites(task_dir, plan.old_rel, plan.new_rel)
1126
- plan.backrefs, plan.unreadable = _plan_backrefs(
1127
- tasks_dir, task_dir, old_name, new_name
1128
- )
1129
- rewritten = {path for path, _linenos, _text in plan.jsonl}
1130
- rewritten.update(path for path, _data, _labels in plan.backrefs)
1131
- plan.reported = _plan_reported_refs(repo_root, task_dir, rewritten, old_name)
1132
-
1133
- for line in _render_rename_plan(plan, repo_root):
1134
- print(line)
1135
-
1136
- for json_path in plan.unreadable:
1137
- print(
1138
- colored(
1139
- f"Warning: {_repo_relative_path(json_path, repo_root)} could not be read; "
1140
- "any back-reference in it is left as-is.",
1141
- Colors.YELLOW,
1142
- ),
1143
- file=sys.stderr,
1144
- )
1145
-
1146
- if getattr(args, "dry_run", False):
1147
- print(colored("Dry run: nothing was written.", Colors.YELLOW), file=sys.stderr)
1148
- return 0
1149
-
1150
- rc = _apply_rename(plan, repo_root)
1151
- if rc != 0:
1152
- return rc
1153
-
1154
- print(colored(f"Renamed: {old_name} -> {new_name}", Colors.GREEN), file=sys.stderr)
1155
- if plan.reported:
1156
- print(
1157
- colored(
1158
- f"{len(plan.reported)} reference(s) elsewhere under {DIR_WORKFLOW}/ "
1159
- "still name the old task; they are listed above and were not rewritten.",
1160
- Colors.YELLOW,
1161
- ),
1162
- file=sys.stderr,
1163
- )
1164
- return 0
1165
-
1166
-
1167
- # =============================================================================
1168
- # Command: archive
1169
- # =============================================================================
1170
-
1171
- def _task_branch_field(data: dict, key: str) -> str:
1172
- """Read a branch field as a trimmed string ("" when unset or not a string)."""
1173
- value = data.get(key)
1174
- return strip_blank(value) if isinstance(value, str) else ""
1175
-
1176
-
1177
- def _validate_branch_metadata(
1178
- data: dict,
1179
- task_name: str,
1180
- repo_root: Path,
1181
- skip: bool,
1182
- ) -> bool:
1183
- """Check branch metadata before the task leaves the active tree.
1184
-
1185
- Returns False when archiving must stop. Archive is the last gate that sees
1186
- a task, so metadata nobody can reconstruct afterwards is refused here
1187
- rather than repaired by hand later (#399 follow-up).
1188
-
1189
- "PR-backed" is deliberately pragmatic: a task carrying a base_branch in a
1190
- repo that has a remote was created expecting a PR, so a missing `branch`
1191
- means the metadata was never recorded — not that the work had no branch.
1192
- Local-only repos and tasks without a base_branch are left alone.
1193
-
1194
- A recorded branch that no longer exists locally stays a warning: after a
1195
- merge the feature branch is normally deleted, and refusing to archive then
1196
- would be backwards.
1197
- """
1198
- branch = _task_branch_field(data, "branch")
1199
- base_branch = _task_branch_field(data, "base_branch")
1200
- task_py = f"python3 {DIR_WORKFLOW}/scripts/task.py"
1201
-
1202
- if branch and not branch_exists_locally(branch, repo_root):
1203
- print(
1204
- colored(
1205
- f"Warning: recorded branch '{branch}' no longer exists locally "
1206
- "(likely merged and deleted).",
1207
- Colors.YELLOW,
1208
- ),
1209
- file=sys.stderr,
1210
- )
1211
-
1212
- if skip:
1213
- return True
1214
-
1215
- if branch and base_branch and branch == base_branch:
1216
- print(
1217
- colored(
1218
- f"Error: refusing to archive '{task_name}': branch and base_branch "
1219
- f"are both '{branch}'. A PR cannot target its own branch, so this "
1220
- "metadata cannot describe the work that was merged.",
1221
- Colors.RED,
1222
- ),
1223
- file=sys.stderr,
1224
- )
1225
- print("Repair whichever field is wrong:", file=sys.stderr)
1226
- print(f" {task_py} set-branch {task_name} <feature-branch>", file=sys.stderr)
1227
- print(f" {task_py} set-base-branch {task_name} <target-branch>", file=sys.stderr)
1228
- print(
1229
- f" {task_py} archive {task_name} --skip-branch-validation"
1230
- " # only if this task was never PR-backed",
1231
- file=sys.stderr,
1232
- )
1233
- return False
1234
-
1235
- if not branch and base_branch and has_git_remote(repo_root):
1236
- print(
1237
- colored(
1238
- f"Error: refusing to archive '{task_name}': no branch is recorded, "
1239
- f"but the task targets base_branch '{base_branch}' in a repo with a "
1240
- "remote — the branch it was built on was never written down.",
1241
- Colors.RED,
1242
- ),
1243
- file=sys.stderr,
1244
- )
1245
- print("Repair with:", file=sys.stderr)
1246
- print(f" {task_py} set-branch {task_name} <branch>", file=sys.stderr)
1247
- print(
1248
- f" {task_py} archive {task_name} --skip-branch-validation"
1249
- " # only if the work landed without a branch of its own",
1250
- file=sys.stderr,
1251
- )
1252
- return False
1253
-
1254
- return True
1255
-
1256
-
1257
- def cmd_archive(args: argparse.Namespace) -> int:
1258
- """Archive completed task."""
1259
- repo_root = get_repo_root()
1260
- task_name = args.name
1261
-
1262
- if not task_name:
1263
- print(colored("Error: Task name is required", Colors.RED), file=sys.stderr)
1264
- return 1
1265
-
1266
- tasks_dir = get_tasks_dir(repo_root)
1267
-
1268
- # Resolve task directory (supports task name, relative path, or absolute path)
1269
- task_dir = resolve_task_dir(task_name, repo_root)
1270
-
1271
- if task_dir is None or not task_dir.is_dir():
1272
- if task_dir is None:
1273
- # resolve_task_dir already reported why; keep the archive-specific
1274
- # refusal so it reads the same as the is_within_tasks_dir guard.
1275
- print(colored(
1276
- f"Error: refusing to archive '{task_name}': "
1277
- f"it does not resolve to a task under {tasks_dir}",
1278
- Colors.RED), file=sys.stderr)
1279
- else:
1280
- print(colored(f"Error: Task not found: {task_name}", Colors.RED), file=sys.stderr)
1281
- print("Active tasks:", file=sys.stderr)
1282
- # Import lazily to avoid circular dependency
1283
- from .tasks import iter_active_tasks
1284
- for t in iter_active_tasks(tasks_dir):
1285
- print(f" - {t.dir_name}/", file=sys.stderr)
1286
- return 1
1287
-
1288
- # Refuse to archive anything that isn't a real task directly under
1289
- # .trellis/tasks/. resolve_task_dir keeps the target inside the tasks dir;
1290
- # this narrows it further to a direct child, so an already-archived task
1291
- # (.trellis/tasks/archive/<month>/<task>) is not archived a second time.
1292
- if not is_within_tasks_dir(task_dir, repo_root):
1293
- print(colored(
1294
- f"Error: refusing to archive '{task_name}': "
1295
- f"{task_dir} is not a task under {tasks_dir}",
1296
- Colors.RED), file=sys.stderr)
1297
- return 1
1298
-
1299
- # Check the destination before anything below mutates task state. The
1300
- # mover refuses a collision too, but by then this command has already
1301
- # marked the task completed, re-parented its children and cleared the
1302
- # sessions pointing at it — all of which would have to be undone by hand.
1303
- archive_dest_check = archive_destination_for(task_dir)
1304
- if archive_dest_check.exists():
1305
- print(colored(
1306
- f"Error: refusing to archive '{task_name}': "
1307
- f"archive destination already exists: "
1308
- f"{_repo_relative_path(archive_dest_check, repo_root)}",
1309
- Colors.RED), file=sys.stderr)
1310
- print(f"Task remains at: {_repo_relative_path(task_dir, repo_root)}", file=sys.stderr)
1311
- print("Move or rename the existing archived task, then retry.", file=sys.stderr)
1312
- return 1
1313
-
1314
- dir_name = task_dir.name
1315
- task_json_path = task_dir / FILE_TASK_JSON
1316
-
1317
- # Update status before archiving
1318
- today = datetime.now().strftime("%Y-%m-%d")
1319
- # Names of child task dirs whose task.json gets modified below; passed
1320
- # into safe_archive_paths_to_add so they're staged in this commit.
1321
- modified_children: list[str] = []
1322
- if task_json_path.is_file():
1323
- data, read_reason = read_json_checked(task_json_path)
1324
- if data is None:
1325
- # Archiving is still the right outcome for a task whose task.json
1326
- # is broken — but say so, or the missing "completed" status looks
1327
- # like the archive silently did half its job.
1328
- problem, _ = describe_json_read_failure(task_json_path, read_reason)
1329
- print(
1330
- colored(
1331
- f"Warning: {problem}; archiving without updating status/children.",
1332
- Colors.YELLOW,
1333
- ),
1334
- file=sys.stderr,
1335
- )
1336
- else:
1337
- # Before any mutation: branch metadata is unrecoverable once the
1338
- # task leaves the active tree. Stale branches only warn.
1339
- if not _validate_branch_metadata(
1340
- data,
1341
- task_name,
1342
- repo_root,
1343
- getattr(args, "skip_branch_validation", False),
1344
- ):
1345
- print(
1346
- f"Not archived: {_repo_relative_path(task_dir, repo_root)} is unchanged.",
1347
- file=sys.stderr,
1348
- )
1349
- return 1
1350
-
1351
- data["status"] = "completed"
1352
- data["completedAt"] = today
1353
- if not write_json(task_json_path, data):
1354
- _report_write_failure(task_json_path)
1355
- print(
1356
- f"Not archived: {_repo_relative_path(task_dir, repo_root)} is unchanged. "
1357
- "Archiving a task still marked in progress would hide it from `list` "
1358
- "with the wrong status.",
1359
- file=sys.stderr,
1360
- )
1361
- return 1
1362
-
1363
- # Handle subtask relationships on archive.
1364
- # Keep this task in its parent's children list so progress
1365
- # counters (children_progress) stay consistent — children
1366
- # missing from the active set are treated as completed.
1367
- task_children = data.get("children", [])
1368
-
1369
- # If this is a parent, clear parent field in all children.
1370
- # Remember each link removed so a later failure in this loop can
1371
- # put it back (see _restore_child_links). Keyed by the child's
1372
- # task.json: a `children` list that names the same child twice
1373
- # would otherwise record a second, already-cleared snapshot and
1374
- # the restore would write that `null` back over the real parent.
1375
- unlinked_children: dict[Path, str | None] = {}
1376
- if task_children:
1377
- for child_name in task_children:
1378
- child_dir_path = find_task_by_name(child_name, tasks_dir)
1379
- if child_dir_path:
1380
- child_json = child_dir_path / FILE_TASK_JSON
1381
- if child_json.is_file():
1382
- child_data, child_reason = read_json_checked(child_json)
1383
- if child_data is None:
1384
- problem, _ = describe_json_read_failure(child_json, child_reason)
1385
- print(
1386
- colored(
1387
- f"Warning: {problem}; child '{child_dir_path.name}' "
1388
- "keeps its parent reference.",
1389
- Colors.YELLOW,
1390
- ),
1391
- file=sys.stderr,
1392
- )
1393
- continue
1394
- # Only the first visit to a child records its original
1395
- # parent: a `children` list naming the same child twice
1396
- # would otherwise snapshot the already-cleared value and
1397
- # the restore would write that `null` back over the link.
1398
- first_visit = child_json not in unlinked_children
1399
- original_parent = child_data.get("parent")
1400
- if first_visit:
1401
- unlinked_children[child_json] = original_parent
1402
- child_data["parent"] = None
1403
- if not write_json(child_json, child_data):
1404
- # Stop before the move: a child pointing at a
1405
- # parent that has left .trellis/tasks/ is a
1406
- # dangling reference nothing repairs later.
1407
- # Put back the children already unlinked above —
1408
- # their parent is staying, so losing the link the
1409
- # other way round is just as unrecoverable.
1410
- # Retrying is safe — every step so far is
1411
- # idempotent.
1412
- if first_visit:
1413
- # The link never came off, so there is nothing
1414
- # to put back for this child.
1415
- del unlinked_children[child_json]
1416
- _restore_child_links(unlinked_children)
1417
- _report_write_failure(child_json)
1418
- print(
1419
- f"Not archived: {_repo_relative_path(task_dir, repo_root)} is "
1420
- f"marked completed but stays in place because child "
1421
- f"'{child_dir_path.name}' could not be unlinked. "
1422
- "Fix the child, then run archive again.",
1423
- file=sys.stderr,
1424
- )
1425
- return 1
1426
- modified_children.append(child_dir_path.name)
1427
-
1428
- # Clear any session that still points at this task before the path moves.
1429
- from .active_task import clear_task_from_sessions
1430
- clear_task_from_sessions(str(task_dir), repo_root)
1431
-
1432
- # Archive
1433
- result = archive_task_complete(task_dir, repo_root)
1434
- if "archived_to" in result:
1435
- archive_dest = Path(result["archived_to"])
1436
- year_month = archive_dest.parent.name
1437
- print(colored(f"Archived: {dir_name} -> archive/{year_month}/", Colors.GREEN), file=sys.stderr)
1438
-
1439
- # Auto-commit unless --no-commit
1440
- if not getattr(args, "no_commit", False):
1441
- if not _auto_commit_archive(dir_name, repo_root, modified_children):
1442
- print(
1443
- colored(
1444
- "Archive moved on disk, but git auto-commit did not complete. "
1445
- "Resolve `git status` before continuing.",
1446
- Colors.RED,
1447
- ),
1448
- file=sys.stderr,
1449
- )
1450
- return 1
1451
-
1452
- # Return the archive path
1453
- print(f"{DIR_WORKFLOW}/{DIR_TASKS}/{DIR_ARCHIVE}/{year_month}/{dir_name}")
1454
-
1455
- # Run hooks with the archived path
1456
- archived_json = archive_dest / FILE_TASK_JSON
1457
- run_task_hooks("after_archive", archived_json, repo_root)
1458
- return 0
1459
-
1460
- return 1
1461
-
1462
-
1463
- def _auto_commit_archive(
1464
- task_name: str,
1465
- repo_root: Path,
1466
- modified_children: list[str] | None = None,
1467
- ) -> bool:
1468
- """Stage Trellis-owned task paths and commit after archive.
1469
-
1470
- Scoped narrowly to the archived task's source + destination paths
1471
- plus any child task dirs whose ``task.json`` was edited (parent →
1472
- children relationship update). Dirty changes in OTHER active task
1473
- dirs are NOT bundled into the archive commit.
1474
-
1475
- If ``.gitignore`` blocks the paths, we warn + skip — we do NOT
1476
- retry with ``git add -f``. The warning explicitly forbids
1477
- ``git add -f .trellis/`` (which would fan out to caches/backups)
1478
- and points users at ``session_auto_commit: false``.
1479
-
1480
- Honors ``session_auto_commit`` in ``.trellis/config.yaml``: when
1481
- set to ``false``, this function returns immediately without
1482
- touching git (the archive directory move on disk is unaffected).
1483
- """
1484
- if not get_session_auto_commit(repo_root):
1485
- print(
1486
- "[OK] session_auto_commit: false — skipping git stage/commit.",
1487
- file=sys.stderr,
1488
- )
1489
- return True
1490
-
1491
- source_rel = f"{DIR_WORKFLOW}/{DIR_TASKS}/{task_name}"
1492
- rc, tracked_out, _ = run_git(
1493
- ["ls-files", "--", source_rel],
1494
- cwd=repo_root,
1495
- )
1496
- source_was_tracked = rc == 0 and bool(tracked_out.strip())
1497
-
1498
- paths = safe_archive_paths_to_add(
1499
- repo_root, task_name=task_name, modified_children=modified_children
1500
- )
1501
- if not paths:
1502
- print("[OK] No task changes to commit.", file=sys.stderr)
1503
- return True
1504
-
1505
- success, _, err = safe_git_add(paths, repo_root, retry_on_index_lock=True)
1506
- if not success:
1507
- if err and "ignored by" in err.lower():
1508
- print_gitignore_warning(paths)
1509
- elif stderr_indicates_index_lock(err):
1510
- _print_index_lock_warning(
1511
- "git add", task_name, repo_root, [*paths, source_rel]
1512
- )
1513
- else:
1514
- print(
1515
- f"[WARN] git add failed: {err.strip() if err else 'unknown error'}",
1516
- file=sys.stderr,
1517
- )
1518
- return not source_was_tracked
1519
-
1520
- # Belt-and-suspenders for the phantom-delete bug: `safe_git_add` uses
1521
- # `git add` (no -A) which only stages additions/modifications. The
1522
- # source task directory was moved away by `shutil.move`, so its files
1523
- # need an explicit `git rm --cached` to stage the deletions in this
1524
- # same commit — otherwise they sit as uncommitted "phantom deletes"
1525
- # against HEAD until something later picks them up.
1526
- #
1527
- # `--ignore-unmatch` makes this a no-op when the task was never tracked
1528
- # (e.g. archiving a task that lived only in working tree).
1529
- rc, _, err = run_git_retry_index_lock(
1530
- ["rm", "-r", "--cached", "--ignore-unmatch", "--", source_rel],
1531
- cwd=repo_root,
1532
- )
1533
- if rc != 0 and stderr_indicates_index_lock(err):
1534
- # Committing now would record the archived copy without the
1535
- # source-side deletes — a half-archived tree in history.
1536
- _print_index_lock_warning(
1537
- "git rm --cached", task_name, repo_root, [*paths, source_rel]
1538
- )
1539
- return not source_was_tracked
1540
-
1541
- rc, _, _ = run_git(
1542
- ["diff", "--cached", "--quiet", "--", *paths, source_rel],
1543
- cwd=repo_root,
1544
- )
1545
- if rc == 0:
1546
- print("[OK] No task changes to commit.", file=sys.stderr)
1547
- return True
1548
-
1549
- commit_msg = f"chore(task): archive {task_name}"
1550
- # Commit with an explicit pathspec: a bare `git commit` would sweep any
1551
- # unrelated entries the developer had staged before archiving into the
1552
- # chore commit (#579). `source_rel` is included so the source-side
1553
- # deletions staged above land in the same commit.
1554
- rc, _, err = run_git_retry_index_lock(
1555
- ["commit", "-m", commit_msg, "--", *paths, source_rel], cwd=repo_root
1556
- )
1557
- if rc == 0:
1558
- print(f"[OK] Auto-committed: {commit_msg}", file=sys.stderr)
1559
- return True
1560
- elif stderr_indicates_index_lock(err):
1561
- _print_index_lock_warning(
1562
- "git commit", task_name, repo_root, [*paths, source_rel]
1563
- )
1564
- return not source_was_tracked
1565
- else:
1566
- print(f"[WARN] Auto-commit failed: {err.strip()}", file=sys.stderr)
1567
- return not source_was_tracked
1568
-
1569
-
1570
- def _print_index_lock_warning(
1571
- action: str, task_name: str, repo_root: Path, paths: list[str]
1572
- ) -> None:
1573
- """Report an archive auto-commit that gave up on a held index.lock.
1574
-
1575
- The move itself already succeeded, so the state is consistent — the task
1576
- lives in archive/ and its changes are staged-or-not but never half of
1577
- both in a commit. Only the commit is outstanding, which the user (or an
1578
- agent reading the log) has to finish by hand.
1579
-
1580
- ``paths`` are the paths the auto-commit would have staged, so the manual
1581
- command keeps the same narrow scope — a blanket ``git add -A -- .trellis/``
1582
- would sweep dirty changes from other active tasks into the archive commit.
1583
- """
1584
- lock = index_lock_path(repo_root)
1585
- print(
1586
- f"[WARN] {action} gave up after {INDEX_LOCK_RETRY_ATTEMPTS} attempts: "
1587
- f"another process is holding {lock}",
1588
- file=sys.stderr,
1589
- )
1590
- print(
1591
- "[WARN] The task was moved into archive/ on disk; only the commit is pending.",
1592
- file=sys.stderr,
1593
- )
1594
- print(
1595
- "[WARN] Close whatever holds the lock (an IDE git integration, a status",
1596
- file=sys.stderr,
1597
- )
1598
- print(
1599
- f"[WARN] daemon, another session), or delete {lock} if it is stale, then",
1600
- file=sys.stderr,
1601
- )
1602
- print(
1603
- f'[WARN] commit manually: git add -A -- {" ".join(paths)} && '
1604
- f'git commit -m "chore(task): archive {task_name}"',
1605
- file=sys.stderr,
1606
- )
1607
-
1608
-
1609
- # =============================================================================
1610
- # Command: add-subtask
1611
- # =============================================================================
1612
-
1613
- def cmd_add_subtask(args: argparse.Namespace) -> int:
1614
- """Link a child task to a parent task."""
1615
- repo_root = get_repo_root()
1616
-
1617
- parent_dir = resolve_task_dir(args.parent_dir, repo_root)
1618
- child_dir = resolve_task_dir(args.child_dir, repo_root)
1619
- if parent_dir is None or child_dir is None:
1620
- return 1
1621
-
1622
- if not parent_dir:
1623
- print(colored(f"Error: Parent task.json not found: {args.parent_dir}", Colors.RED), file=sys.stderr)
1624
- return 1
1625
-
1626
- if not child_dir:
1627
- print(colored(f"Error: Child task.json not found: {args.child_dir}", Colors.RED), file=sys.stderr)
1628
- return 1
1629
-
1630
- parent_json_path = parent_dir / FILE_TASK_JSON
1631
- child_json_path = child_dir / FILE_TASK_JSON
1632
-
1633
- if not parent_json_path.is_file():
1634
- print(colored(f"Error: Parent task.json not found: {args.parent_dir}", Colors.RED), file=sys.stderr)
1635
- return 1
1636
-
1637
- if not child_json_path.is_file():
1638
- print(colored(f"Error: Child task.json not found: {args.child_dir}", Colors.RED), file=sys.stderr)
1639
- return 1
1640
-
1641
- parent_data, parent_reason = read_json_checked(parent_json_path)
1642
- if parent_data is None:
1643
- _report_read_failure(parent_json_path, parent_reason)
1644
- return 1
1645
- child_data, child_reason = read_json_checked(child_json_path)
1646
- if child_data is None:
1647
- _report_read_failure(child_json_path, child_reason)
1648
- return 1
1649
-
1650
- # Check if child already has a parent
1651
- existing_parent = child_data.get("parent")
1652
- if existing_parent:
1653
- print(colored(f"Error: Child task already has a parent: {existing_parent}", Colors.RED), file=sys.stderr)
1654
- return 1
1655
-
1656
- # Add child to parent's children list
1657
- parent_children = _ensure_children_list(parent_data)
1658
- child_dir_name = child_dir.name
1659
- if child_dir_name not in parent_children:
1660
- parent_children.append(child_dir_name)
1661
- parent_data["children"] = parent_children
1662
-
1663
- # Set parent in child's task.json
1664
- child_data["parent"] = parent_dir.name
1665
-
1666
- # Write both. A link is two files; if the second write fails silently the
1667
- # two sides disagree with no error, so check each and name the side that
1668
- # did land so the user knows what to undo.
1669
- if not write_json(parent_json_path, parent_data):
1670
- print(colored(f"Error: Failed to write parent task.json: {parent_json_path}", Colors.RED), file=sys.stderr)
1671
- print("No link was written.", file=sys.stderr)
1672
- return 1
1673
- if not write_json(child_json_path, child_data):
1674
- print(colored(f"Error: Failed to write child task.json: {child_json_path}", Colors.RED), file=sys.stderr)
1675
- print(
1676
- f"Link is half-written: {parent_json_path} now lists "
1677
- f"'{child_dir.name}' as a child, but the child does not record the parent.",
1678
- file=sys.stderr,
1679
- )
1680
- return 1
1681
-
1682
- print(colored(f"Linked: {child_dir.name} -> {parent_dir.name}", Colors.GREEN), file=sys.stderr)
1683
- return 0
1684
-
1685
-
1686
- # =============================================================================
1687
- # Command: remove-subtask
1688
- # =============================================================================
1689
-
1690
- def cmd_remove_subtask(args: argparse.Namespace) -> int:
1691
- """Unlink a child task from a parent task."""
1692
- repo_root = get_repo_root()
1693
-
1694
- parent_dir = resolve_task_dir(args.parent_dir, repo_root)
1695
- child_dir = resolve_task_dir(args.child_dir, repo_root)
1696
- if parent_dir is None or child_dir is None:
1697
- return 1
1698
-
1699
- if not parent_dir:
1700
- print(colored(f"Error: Parent task.json not found: {args.parent_dir}", Colors.RED), file=sys.stderr)
1701
- return 1
1702
-
1703
- if not child_dir:
1704
- print(colored(f"Error: Child task.json not found: {args.child_dir}", Colors.RED), file=sys.stderr)
1705
- return 1
1706
-
1707
- parent_json_path = parent_dir / FILE_TASK_JSON
1708
- child_json_path = child_dir / FILE_TASK_JSON
1709
-
1710
- if not parent_json_path.is_file():
1711
- print(colored(f"Error: Parent task.json not found: {args.parent_dir}", Colors.RED), file=sys.stderr)
1712
- return 1
1713
-
1714
- if not child_json_path.is_file():
1715
- print(colored(f"Error: Child task.json not found: {args.child_dir}", Colors.RED), file=sys.stderr)
1716
- return 1
1717
-
1718
- parent_data, parent_reason = read_json_checked(parent_json_path)
1719
- if parent_data is None:
1720
- _report_read_failure(parent_json_path, parent_reason)
1721
- return 1
1722
- child_data, child_reason = read_json_checked(child_json_path)
1723
- if child_data is None:
1724
- _report_read_failure(child_json_path, child_reason)
1725
- return 1
1726
-
1727
- # Remove child from parent's children list
1728
- parent_children = _ensure_children_list(parent_data)
1729
- child_dir_name = child_dir.name
1730
- if child_dir_name in parent_children:
1731
- parent_children.remove(child_dir_name)
1732
- parent_data["children"] = parent_children
1733
-
1734
- # Clear parent in child's task.json
1735
- child_data["parent"] = None
1736
-
1737
- # Write both — see cmd_add_subtask: an unchecked second write leaves the
1738
- # two sides disagreeing with no error.
1739
- if not write_json(parent_json_path, parent_data):
1740
- print(colored(f"Error: Failed to write parent task.json: {parent_json_path}", Colors.RED), file=sys.stderr)
1741
- print("Nothing was unlinked.", file=sys.stderr)
1742
- return 1
1743
- if not write_json(child_json_path, child_data):
1744
- print(colored(f"Error: Failed to write child task.json: {child_json_path}", Colors.RED), file=sys.stderr)
1745
- print(
1746
- f"Unlink is half-written: {parent_json_path} no longer lists "
1747
- f"'{child_dir.name}', but the child still records the parent.",
1748
- file=sys.stderr,
1749
- )
1750
- return 1
1751
-
1752
- print(colored(f"Unlinked: {child_dir.name} from {parent_dir.name}", Colors.GREEN), file=sys.stderr)
1753
- return 0
1754
-
1755
-
1756
- # =============================================================================
1757
- # Command: set-branch
1758
- # =============================================================================
1759
-
1760
- def cmd_set_branch(args: argparse.Namespace) -> int:
1761
- """Set git branch for task."""
1762
- repo_root = get_repo_root()
1763
- target_dir = resolve_task_dir(args.dir, repo_root)
1764
- if target_dir is None:
1765
- return 1
1766
- branch = args.branch
1767
-
1768
- if not branch:
1769
- print(colored("Error: Missing arguments", Colors.RED))
1770
- print("Usage: python3 task.py set-branch <task-dir> <branch-name>")
1771
- return 1
1772
-
1773
- if not target_dir:
1774
- # target_dir is None here, so it must not appear in the message. This
1775
- # is also the branch a ref pointing outside the repo lands in.
1776
- print(colored(f"Error: Task not found: {args.dir}", Colors.RED))
1777
- return 1
1778
-
1779
- task_json = target_dir / FILE_TASK_JSON
1780
- if not task_json.is_file():
1781
- print(colored(f"Error: task.json not found at {target_dir}", Colors.RED))
1782
- return 1
1783
-
1784
- data, reason = read_json_checked(task_json)
1785
- if data is None:
1786
- _report_read_failure(task_json, reason)
1787
- return 1
1788
-
1789
- data["branch"] = branch
1790
- if not write_json(task_json, data):
1791
- _report_write_failure(task_json)
1792
- return 1
1793
-
1794
- print(colored(f"✓ Branch set to: {branch}", Colors.GREEN))
1795
- return 0
1796
-
1797
-
1798
- # =============================================================================
1799
- # Command: set-base-branch
1800
- # =============================================================================
1801
-
1802
- def cmd_set_base_branch(args: argparse.Namespace) -> int:
1803
- """Set the base branch (PR target) for task."""
1804
- repo_root = get_repo_root()
1805
- target_dir = resolve_task_dir(args.dir, repo_root)
1806
- if target_dir is None:
1807
- return 1
1808
- base_branch = args.base_branch
1809
-
1810
- if not base_branch:
1811
- print(colored("Error: Missing arguments", Colors.RED))
1812
- print("Usage: python3 task.py set-base-branch <task-dir> <base-branch>")
1813
- print("Example: python3 task.py set-base-branch <dir> develop")
1814
- print()
1815
- print("This sets the target branch for PR (the branch your feature will merge into).")
1816
- return 1
1817
-
1818
- if not target_dir:
1819
- # target_dir is None here, so it must not appear in the message. This
1820
- # is also the branch a ref pointing outside the repo lands in.
1821
- print(colored(f"Error: Task not found: {args.dir}", Colors.RED))
1822
- return 1
1823
-
1824
- task_json = target_dir / FILE_TASK_JSON
1825
- if not task_json.is_file():
1826
- print(colored(f"Error: task.json not found at {target_dir}", Colors.RED))
1827
- return 1
1828
-
1829
- data, reason = read_json_checked(task_json)
1830
- if data is None:
1831
- _report_read_failure(task_json, reason)
1832
- return 1
1833
-
1834
- data["base_branch"] = base_branch
1835
- if not write_json(task_json, data):
1836
- _report_write_failure(task_json)
1837
- return 1
1838
-
1839
- print(colored(f"✓ Base branch set to: {base_branch}", Colors.GREEN))
1840
- print(f" PR will target: {base_branch}")
1841
- return 0
1842
-
1843
-
1844
- # =============================================================================
1845
- # Command: set-scope
1846
- # =============================================================================
1847
-
1848
- def cmd_set_scope(args: argparse.Namespace) -> int:
1849
- """Set scope for PR title."""
1850
- repo_root = get_repo_root()
1851
- target_dir = resolve_task_dir(args.dir, repo_root)
1852
- if target_dir is None:
1853
- return 1
1854
- scope = args.scope
1855
-
1856
- if not scope:
1857
- print(colored("Error: Missing arguments", Colors.RED))
1858
- print("Usage: python3 task.py set-scope <task-dir> <scope>")
1859
- return 1
1860
-
1861
- if not target_dir:
1862
- # target_dir is None here, so it must not appear in the message. This
1863
- # is also the branch a ref pointing outside the repo lands in.
1864
- print(colored(f"Error: Task not found: {args.dir}", Colors.RED))
1865
- return 1
1866
-
1867
- task_json = target_dir / FILE_TASK_JSON
1868
- if not task_json.is_file():
1869
- print(colored(f"Error: task.json not found at {target_dir}", Colors.RED))
1870
- return 1
1871
-
1872
- data, reason = read_json_checked(task_json)
1873
- if data is None:
1874
- _report_read_failure(task_json, reason)
1875
- return 1
1876
-
1877
- data["scope"] = scope
1878
- if not write_json(task_json, data):
1879
- _report_write_failure(task_json)
1880
- return 1
1881
-
1882
- print(colored(f"✓ Scope set to: {scope}", Colors.GREEN))
1883
- return 0
1884
-
1885
-
1886
- # =============================================================================
1887
- # Command: set-meta
1888
- # =============================================================================
1889
-
1890
- def cmd_set_meta(args: argparse.Namespace) -> int:
1891
- """Set/overwrite one metadata key on an existing task."""
1892
- repo_root = get_repo_root()
1893
- target_dir = resolve_task_dir(args.dir, repo_root)
1894
- if target_dir is None:
1895
- return 1
1896
- key = args.key
1897
- value = args.value
1898
-
1899
- if not key:
1900
- print(colored("Error: Missing arguments", Colors.RED))
1901
- print("Usage: python3 task.py set-meta <task-dir> <key> <value>")
1902
- return 1
1903
-
1904
- if not target_dir:
1905
- # target_dir is None here, so it must not appear in the message. This
1906
- # is also the branch a ref pointing outside the repo lands in.
1907
- print(colored(f"Error: Task not found: {args.dir}", Colors.RED))
1908
- return 1
1909
-
1910
- task_json = target_dir / FILE_TASK_JSON
1911
- if not task_json.is_file():
1912
- print(colored(f"Error: task.json not found at {target_dir}", Colors.RED))
1913
- return 1
1914
-
1915
- data, reason = read_json_checked(task_json)
1916
- if data is None:
1917
- _report_read_failure(task_json, reason)
1918
- return 1
1919
-
1920
- meta = data.get("meta")
1921
- if not isinstance(meta, dict):
1922
- meta = {}
1923
- meta[key] = value
1924
- data["meta"] = meta
1925
- if not write_json(task_json, data):
1926
- _report_write_failure(task_json)
1927
- return 1
1928
-
1929
- print(colored(f"✓ Meta set: {key} = {value}", Colors.GREEN))
1930
- return 0