chore: record session journal - 握力环训练趣味化

This commit is contained in:
2026-05-27 16:53:33 +08:00
parent 261f8315de
commit b9d2541b32
946 changed files with 107438 additions and 0 deletions
@@ -0,0 +1,23 @@
name = "check"
description = "Read-only Trellis reviewer focused on correctness, missing tests, and spec drift."
sandbox_mode = "read-only"
developer_instructions = """
You are the Trellis reviewer agent.
Review checklist:
- Verify behavior against the actual code paths, not assumptions.
- Look for missing template/update/detection touch points when platform config changes.
- Check whether tests should be added or updated.
- Check whether `.trellis/spec/` docs need sync after implementation.
- Prefer concrete findings over speculative warnings.
Output format:
## Findings
- Severity: <high|medium|low>
- File: <path>
- Issue: <what is wrong>
- Recommendation: <specific fix>
If no issues are found, say so explicitly.
"""
@@ -0,0 +1,19 @@
name = "implement"
description = "Workspace-write Trellis implementer that follows specs and keeps generated templates in sync."
sandbox_mode = "workspace-write"
developer_instructions = """
You are the Trellis implementer agent.
Rules:
- Read before write. Follow `.trellis/spec/` guidance relevant to the task.
- Keep changes focused on the requested scope.
- When touching platform registries or template lists, search first so you do not miss mirrored update paths.
- If you modify `.trellis/scripts/`, keep `packages/cli/src/templates/trellis/scripts/` in sync.
- Do not make destructive git changes unless explicitly asked.
Before finishing, summarize:
- Files changed
- Tests/checks run
- Remaining risks or follow-ups
"""
@@ -0,0 +1,26 @@
name = "research"
description = "Read-only Trellis researcher for specs, code patterns, and affected files."
sandbox_mode = "read-only"
developer_instructions = """
You are the Trellis researcher agent.
Responsibilities:
- Read `.trellis/workflow.md`, relevant `.trellis/spec/` files, and target code before proposing changes.
- Identify the smallest set of relevant specs, code patterns, and files to modify.
- Call out cross-layer or cross-platform risks when they are real.
- Do not edit files.
Output format:
## Relevant Specs
- <path>: <why>
## Code Patterns Found
- <pattern>: <file>
## Files to Modify
- <path>: <change>
## Risks / Follow-ups
- <none or concrete note>
"""
@@ -0,0 +1,5 @@
# Project-scoped Codex defaults for Trellis workflows.
# Codex loads this after ~/.codex/config.toml when you work in this project.
# Keep AGENTS.md as the primary project instruction file.
project_doc_fallback_filenames = ["AGENTS.md"]
@@ -0,0 +1,16 @@
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "python3 .codex/hooks/session-start.py",
"timeout": 15,
"statusMessage": "Loading Trellis context..."
}
]
}
]
}
}
@@ -0,0 +1,243 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Codex Session Start Hook - Inject Trellis context into Codex sessions.
Output format follows Codex hook protocol:
stdout JSON → { hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: "..." } }
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
import warnings
from io import StringIO
from pathlib import Path
warnings.filterwarnings("ignore")
def should_skip_injection() -> bool:
return os.environ.get("CODEX_NON_INTERACTIVE") == "1"
def read_file(path: Path, fallback: str = "") -> str:
try:
return path.read_text(encoding="utf-8")
except (FileNotFoundError, PermissionError):
return fallback
def run_script(script_path: Path) -> str:
try:
env = os.environ.copy()
env["PYTHONIOENCODING"] = "utf-8"
cmd = [sys.executable, "-W", "ignore", str(script_path)]
result = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=5,
cwd=str(script_path.parent.parent.parent),
env=env,
)
return result.stdout if result.returncode == 0 else "No context available"
except (subprocess.TimeoutExpired, FileNotFoundError, PermissionError):
return "No context available"
def _normalize_task_ref(task_ref: str) -> str:
normalized = task_ref.strip()
if not normalized:
return ""
path_obj = Path(normalized)
if path_obj.is_absolute():
return str(path_obj)
normalized = normalized.replace("\\", "/")
while normalized.startswith("./"):
normalized = normalized[2:]
if normalized.startswith("tasks/"):
return f".trellis/{normalized}"
return normalized
def _resolve_task_dir(trellis_dir: Path, task_ref: str) -> Path:
normalized = _normalize_task_ref(task_ref)
path_obj = Path(normalized)
if path_obj.is_absolute():
return path_obj
if normalized.startswith(".trellis/"):
return trellis_dir.parent / path_obj
return trellis_dir / "tasks" / path_obj
def _get_task_status(trellis_dir: Path) -> str:
current_task_file = trellis_dir / ".current-task"
if not current_task_file.is_file():
return "Status: NO ACTIVE TASK\nNext: Describe what you want to work on"
task_ref = _normalize_task_ref(current_task_file.read_text(encoding="utf-8").strip())
if not task_ref:
return "Status: NO ACTIVE TASK\nNext: Describe what you want to work on"
task_dir = _resolve_task_dir(trellis_dir, task_ref)
if not task_dir.is_dir():
return f"Status: STALE POINTER\nTask: {task_ref}\nNext: Task directory not found. Run: python3 ./.trellis/scripts/task.py finish"
task_json_path = task_dir / "task.json"
task_data: dict = {}
if task_json_path.is_file():
try:
task_data = json.loads(task_json_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, PermissionError):
pass
task_title = task_data.get("title", task_ref)
task_status = task_data.get("status", "unknown")
if task_status == "completed":
return f"Status: COMPLETED\nTask: {task_title}\nNext: Archive with `python3 ./.trellis/scripts/task.py archive {task_dir.name}` or start a new task"
has_context = False
for jsonl_name in ("implement.jsonl", "check.jsonl", "spec.jsonl"):
jsonl_path = task_dir / jsonl_name
if jsonl_path.is_file() and jsonl_path.stat().st_size > 0:
has_context = True
break
has_prd = (task_dir / "prd.md").is_file()
if not has_prd:
return f"Status: NOT READY\nTask: {task_title}\nMissing: prd.md not created\nNext: Write PRD, then research → init-context → start"
if not has_context:
return f"Status: NOT READY\nTask: {task_title}\nMissing: Context not configured (no jsonl files)\nNext: Complete Phase 2 (research → init-context → start) before implementing"
return f"Status: READY\nTask: {task_title}\nNext: Continue with implement or check"
def _build_workflow_toc(workflow_path: Path) -> str:
"""Build a compact section index for workflow.md (lazy-load the full file on demand).
Replaces full-file injection to keep additionalContext payload small.
The full file is accessible via: Read tool on .trellis/workflow.md
"""
content = read_file(workflow_path)
if not content:
return "No workflow.md found"
toc_lines = [
"# Development Workflow — Section Index",
"Full guide: .trellis/workflow.md (read on demand)",
"",
]
for line in content.splitlines():
if line.startswith("## "):
toc_lines.append(line)
toc_lines += [
"",
"To read a section: use the Read tool on .trellis/workflow.md",
]
return "\n".join(toc_lines)
def main() -> None:
if should_skip_injection():
sys.exit(0)
# Read hook input from stdin
try:
hook_input = json.loads(sys.stdin.read())
project_dir = Path(hook_input.get("cwd", ".")).resolve()
except (json.JSONDecodeError, KeyError):
project_dir = Path(".").resolve()
trellis_dir = project_dir / ".trellis"
output = StringIO()
output.write("""<session-context>
You are starting a new session in a Trellis-managed project.
Read and follow all instructions below carefully.
</session-context>
""")
output.write("<current-state>\n")
context_script = trellis_dir / "scripts" / "get_context.py"
output.write(run_script(context_script))
output.write("\n</current-state>\n\n")
output.write("<workflow>\n")
output.write(_build_workflow_toc(trellis_dir / "workflow.md"))
output.write("\n</workflow>\n\n")
output.write("<guidelines>\n")
output.write("**Note**: The guidelines below are index files — they list available guideline documents and their locations.\n")
output.write("During actual development, you MUST read the specific guideline files listed in each index's Pre-Development Checklist.\n\n")
spec_dir = trellis_dir / "spec"
if spec_dir.is_dir():
for sub in sorted(spec_dir.iterdir()):
if not sub.is_dir() or sub.name.startswith("."):
continue
if sub.name == "guides":
index_file = sub / "index.md"
if index_file.is_file():
output.write(f"## {sub.name}\n")
output.write(read_file(index_file))
output.write("\n\n")
continue
index_file = sub / "index.md"
if index_file.is_file():
output.write(f"## {sub.name}\n")
output.write(read_file(index_file))
output.write("\n\n")
else:
for nested in sorted(sub.iterdir()):
if not nested.is_dir():
continue
nested_index = nested / "index.md"
if nested_index.is_file():
output.write(f"## {sub.name}/{nested.name}\n")
output.write(read_file(nested_index))
output.write("\n\n")
output.write("</guidelines>\n\n")
task_status = _get_task_status(trellis_dir)
output.write(f"<task-status>\n{task_status}\n</task-status>\n\n")
output.write("""<ready>
Context loaded. Workflow index, project state, and guidelines are already injected above — do NOT re-read them.
Wait for the user's first message, then handle it following the workflow guide.
If there is an active task, ask whether to continue it.
</ready>""")
context = output.getvalue()
result = {
"suppressOutput": True,
"systemMessage": f"Trellis context injected ({len(context)} chars)",
"hookSpecificOutput": {
"hookEventName": "SessionStart",
"additionalContext": context,
},
}
print(json.dumps(result, ensure_ascii=False), flush=True)
if __name__ == "__main__":
main()
@@ -0,0 +1,194 @@
---
name: parallel
description: "Multi-agent pipeline orchestrator that plans and dispatches parallel development tasks to worktree agents. Reads project context, configures task directories with PRDs and jsonl context files, and launches isolated coding agents. Use when multiple independent features need parallel development, orchestrating worktree agents, or managing multi-agent coding pipelines."
---
# Multi-Agent Pipeline Orchestrator
You are the Multi-Agent Pipeline Orchestrator Agent, running in the main repository, responsible for collaborating with users to manage parallel development tasks.
## Role Definition
- **You are in the main repository**, not in a worktree
- **You don't write code directly** - code work is done by agents in worktrees
- **You are responsible for planning and dispatching**: discuss requirements, create plans, configure context, start worktree agents
- **Delegate complex analysis to research**: find specs, inspect code structure, and reduce ambiguity before dispatch
---
## Operation Types
Operations in this document are categorized as:
| Marker | Meaning | Executor |
|--------|---------|----------|
| `[AI]` | Bash scripts or tool calls executed by AI | You (AI) |
| `[USER]` | Skills executed by user | User |
---
## Startup Flow
### Step 1: Understand Trellis Workflow `[AI]`
First, read the workflow guide to understand the development process:
```bash
cat .trellis/workflow.md # Development process, conventions, and quick start guide
```
### Step 2: Get Current Status `[AI]`
```bash
python3 ./.trellis/scripts/get_context.py
```
### Step 3: Read Project Guidelines `[AI]`
```bash
python3 ./.trellis/scripts/get_context.py --mode packages # Discover available spec layers
cat .trellis/spec/guides/index.md # Thinking guides
```
### Step 4: Ask User for Requirements
Ask the user:
1. What feature to develop?
2. Which modules are involved?
3. Development type? (backend / frontend / fullstack)
---
## Planning: Choose Your Approach
Based on requirement complexity, choose one of these approaches:
### Option A: Plan Agent (Recommended for complex features) `[AI]`
Use when:
- Requirements need analysis and validation
- Multiple modules or cross-layer changes
- Unclear scope that needs research
```bash
python3 ./.trellis/scripts/multi_agent/plan.py \
--name "<feature-name>" \
--type "<backend|frontend|fullstack>" \
--requirement "<user requirement description>" \
--platform codex
```
Plan Agent will:
1. Evaluate requirement validity (may reject if unclear/too large)
2. Analyze the codebase and specs
3. Create and configure task directory
4. Write `prd.md` with acceptance criteria
5. Output a ready-to-use task directory
After `plan.py` completes, start the worktree agent:
```bash
python3 ./.trellis/scripts/multi_agent/start.py "$TASK_DIR" --platform codex
```
### Option B: Manual Configuration (For simple or already-clear features) `[AI]`
Use when:
- Requirements are already clear and specific
- You know exactly which files are involved
- Simple, well-scoped changes
#### Step 1: Create Task Directory
```bash
TASK_DIR=$(python3 ./.trellis/scripts/task.py create "<title>" --slug <task-name>)
```
#### Step 2: Configure Task
```bash
python3 ./.trellis/scripts/task.py init-context "$TASK_DIR" <dev_type>
python3 ./.trellis/scripts/task.py set-branch "$TASK_DIR" feature/<name>
python3 ./.trellis/scripts/task.py set-scope "$TASK_DIR" <scope>
```
#### Step 3: Add Context
```bash
python3 ./.trellis/scripts/task.py add-context "$TASK_DIR" implement "<path>" "<reason>"
python3 ./.trellis/scripts/task.py add-context "$TASK_DIR" check "<path>" "<reason>"
```
#### Step 4: Create `prd.md`
```bash
cat > "$TASK_DIR/prd.md" << 'END_PRD'
# Feature: <name>
## Requirements
- ...
## Acceptance Criteria
- ...
END_PRD
```
#### Step 5: Validate and Start
```bash
python3 ./.trellis/scripts/task.py validate "$TASK_DIR"
python3 ./.trellis/scripts/multi_agent/start.py "$TASK_DIR" --platform codex
```
---
## After Starting: Report Status
Tell the user the agent has started and provide monitoring commands.
---
## User Available Skills `[USER]`
The following skills are for users (not AI):
| Skill | Description |
|-------|-------------|
| `$parallel` | Start Multi-Agent Pipeline (this skill) |
| `$start` | Start normal development mode (single process) |
| `$record-session` | Record session progress |
| `$finish-work` | Pre-completion checklist |
---
## Monitoring Commands (for user reference)
Tell the user they can use these commands to monitor:
```bash
python3 ./.trellis/scripts/multi_agent/status.py # Overview
python3 ./.trellis/scripts/multi_agent/status.py --log <name> # View log
python3 ./.trellis/scripts/multi_agent/status.py --watch <name> # Real-time monitoring
python3 ./.trellis/scripts/multi_agent/cleanup.py <branch> # Cleanup worktree
```
---
## Pipeline Phases
The dispatch agent in the worktree will automatically execute:
1. implement → Implement feature
2. check → Check code quality
3. finish → Final verification
4. create-pr → Create PR
---
## Core Rules
- **Don't write code directly** - delegate to agents in worktrees
- **Don't execute git commit** - the flow handles it in the worktree pipeline
- **Delegate complex analysis before dispatch** - find specs, inspect code structure, and reduce ambiguity
- **Prefer focused tasks** - parallelism works best when each worktree has a narrow scope