升级Trellis并精简项目知识(09-05-trellis-upgrade-rule-cleanup)

更新Trellis适配、任务归属与归档失败恢复,精简技能入口和知识读取规则。
保留权限、证据、事务及独立复核合同;纳入对应任务及已完成复核记录。
仅本地提交,不启用新平台适配,不推送或部署。
这个提交包含在:
2026-09-19 13:10:06 +08:00
父节点 b1d25d3c99
当前提交 729d90576f
共修改 25 个文件,包含 550 行新增和 1328 行删除
+5 -7
查看文件
@@ -5,11 +5,9 @@ description: "Load the task and affected-layer guidelines before implementation
# Before Development
1. Read the current PRD and applicable design/implementation notes if not already current in context.
2. Identify the smallest behavior gap, affected files, exclusions and validation commands. Reuse the approved plan rather than writing another checklist.
3. Discover package indexes only when the affected layer is unknown. Read its relevant coding and quality contracts; follow references needed for this change.
4. Read cross-layer or reuse guides only when shared contracts, multiple layers, shared constants or new abstractions are involved.
5. Once the plan is approved, continue through implementation and relevant validation. Ask again only for material changes to scope, risk or acceptance, or separately protected operations.
6. Keep unrelated dirty files and pre-existing failures out of scope. A local refactor requires evidence that behavior stays unchanged.
1. Reuse the current PRD and approved plan; load missing design/implementation context. Identify the behavior gap, affected files, exclusions and meaningful checks.
2. Locate affected-layer contracts through the package index. For large specs use `rg -n '^#{1,3} ' <file>`, then read general rules, complete relevant sections and required references. Expand for shared/cross-layer contracts; a search excerpt is not full coverage. Reuse unchanged context.
3. Continue approved implementation and validation. Ask again only for material changes to scope, risk or acceptance, or separately protected operations.
4. Preserve unrelated dirty files and pre-existing failures. Verify behavior for local refactors; choose checks for this change, not full business testing for rule-only edits.
Do not force full document reads, repeat unchanged context, require unavailable tools, or turn a rule-only task into full business testing. Preserve privacy, production and independent-review boundaries from AGENTS.md.
Keep privacy, production and independent-review boundaries from AGENTS.md. Use supported fallbacks for unavailable optional tools.
+11 -190
查看文件
@@ -1,200 +1,21 @@
---
name: trellis-brainstorm
description: "Guides collaborative requirements discovery before implementation. Creates task directory, seeds PRD, asks high-value questions one at a time, researches technical choices, and converges on MVP scope. Use when requirements are unclear, there are multiple valid approaches, or the user describes a new feature or complex task."
description: "Resolve unclear requirements and consequential design choices before implementation; produce or update the owning Trellis plan."
---
# Trellis Brainstorm
# Plan The Requested Change
## Non-Negotiable Planning Contract
Use the project's workflow and task contract. Reuse a suitable task; create one only when needed and authorized. Task creation alone is not implementation approval. Keep unrelated tasks and historical evidence intact.
A request to build, implement, fix, refactor, or "go ahead" is not approval to leave planning. Task-creation consent is also not implementation approval.
Inspect relevant code, tests and fact sources before asking questions. Separate observed behavior from intended behavior: existing code is evidence, not authority to redefine the user's goal. Search past dialogue only when a necessary decision is missing from current context and task records.
For non-trivial work, present the plan and obtain approval before implementation. Approval of the same plan in prior turns remains valid; clerical backfill, unchanged artifacts or repeated planning breadcrumbs do not restart the approval gate. Once decisions and required artifacts are complete, start and execute the approved scope.
Resolve routine implementation choices within the user's authorized scope. Ask about consequential product, compatibility, UX, risk or acceptance decisions that remain unclear; state the recommendation and trade-off. A blocking answer is required before dependent work, while independent evidence gathering may continue. Do not invent questions or treat silence as approval.
While any user-owned product, scope, UX, compatibility, risk, or acceptance decision remains unresolved, end the turn with exactly one highest-value question. Do not edit product code, dispatch implementation, or run `task.py start`.
Record the smallest plan that makes the work reviewable:
- `prd.md`: goal, relevant facts, scope/exclusions, observable acceptance, test plan and unresolved decisions.
- Complex work also needs `design.md` for contracts, trade-offs and rollout/rollback, plus `implement.md` for ordered work and checks. Lightweight tasks may be PRD-only.
- Context manifests contain stable spec/research only. Sub-agent mode requires curated real entries; empty/legacy seed-only manifests do not qualify. Inline mode reads context directly and permits empty manifests.
## Non-Negotiable Evidence Rule
Before requesting a new plan's approval, resolve blocking questions and consolidate temporary notes into the owning sections. Preserve requirement IDs, evidence anchors, decisions and acceptance mappings; do not rewrite an already clear PRD merely to satisfy a template. Defer technical unknowns explicitly only when doing so does not silently change required behavior.
If a question can be answered by exploring the codebase, explore the codebase instead.
This is mandatory. Before asking the user a question, first check whether the answer is already available in code, tests, configs, docs, existing specs, or task history.
Do not ask the user to confirm facts that the repository can answer. Ask only for product intent, preference, scope, risk tolerance, acceptance behavior, or decisions that remain ambiguous after inspection.
Repository evidence establishes current behavior and technical constraints. The user's intended behavior, feature scope boundaries, and UX preferences are never answerable by repository evidence alone, even when an existing pattern exists; existing patterns are options and recommendation evidence, not decisions.
---
Use this skill during Phase 1 planning to turn the user's request into clear requirements and planning artifacts.
## Preconditions
Use this skill only after task-creation consent has been given and the user is ready to enter Trellis planning.
If no task exists yet, create one:
```bash
TASK_DIR=$(python3 ./.trellis/scripts/task.py create "<short task title>" --description "<one-line summary>" --slug <slug>)
```
Use a concise title from the user's request. Both the title and `--description` must be non-empty — `create` rejects blanks, and a record with either one empty is refused at archive. Use a slug without a date prefix. `task.py create` adds the `MM-DD-` directory prefix automatically.
`task.py create` creates the default `prd.md`. Update that file with the current understanding before asking follow-up questions.
## Planning Flow
1. Capture the user's request and initial known facts in `prd.md`.
2. Inspect available evidence before asking questions:
- code, tests, fixtures, and configs
- README files, docs, existing specs, and domain notes
- related Trellis tasks, research files, and session history when present
3. Separate what you found into:
- confirmed facts
- product intent still needed from the user
- scope or risk decisions still needed from the user
- likely out-of-scope items
4. If a user-owned decision remains, ask the single highest-value question, include your recommendation and trade-off, then stop. Do not perform implementation work in the same turn.
5. After each user answer, update `prd.md`, recompute the decision inventory, and repeat from step 2.
6. When no user-owned decision remains, create or update `design.md` and `implement.md` for complex tasks.
7. Run the requirement convergence gate, then the PRD convergence pass.
8. If this plan has not yet been approved, present its final summary and wait. If the same scope has already been approved, do not ask again.
9. With recorded approval and complete artifacts, run `task.py start` and implement. Repeat review only for a material scope, risk or acceptance change.
Do not invent a project-specific product/spec hierarchy. If the repository already has product, domain, or spec docs, use them. If it does not, proceed with the evidence that exists.
## Question Rules
Ask only one question per message.
Each question must include:
- the decision needed
- why the answer matters
- your recommended answer
- the trade-off if the user chooses differently
Do not ask process questions such as whether to search, inspect files, or continue brainstorming. Do the evidence work directly. Ask the user only when the remaining issue is a product decision, preference, scope boundary, or risk tolerance choice.
Recommendations are not default selections. Never choose a recommended product decision on the user's behalf merely because the user asked for implementation.
Do not manufacture clarification questions. Present a new plan for approval when needed; if the same plan is already approved and artifacts are complete, start implementation.
Final review is required for a new or materially changed plan, not for reformatting an already approved plan. Task-creation consent alone is not implementation approval.
## Thinking Framework: First Principles Analysis
When requirements are vague, solutions feel over-engineered, or you're about to add complexity "because everyone does" — decompose to fundamental truths before reasoning upward.
### Step 1: Restate the Problem
Strip away implementation details to one sentence.
> Bad: "We need to add Redis caching to the user profile endpoint"
> Good: "User profile data takes too long to load"
### Step 2: List Fundamental Truths
What is absolutely true (not opinion or convention)?
| Category | Examples |
|----------|----------|
| **Physical constraints** | Network latency ≥ 0, disk I/O has limits |
| **Business rules** | "Users must see their own data" |
| **Technical invariants** | "Data must be consistent" |
| **User needs** | "The user wants X within Y seconds" |
### Step 3: Challenge Assumptions
For each component of the current plan:
- **Fact or convention?** "We always use REST" — why?
- **What if we removed this?** If nothing breaks, it's unnecessary.
- **Solving the actual problem or a symptom?** Trace the causal chain.
- **Who benefits from this complexity?** If "nobody", simplify.
### Step 4: Build Up from Truths
1. Start with the minimum viable mechanism satisfying all truths
2. Add complexity only when a specific truth demands it
3. Each addition must answer: "Which truth requires this?"
### Step 5: Validate
- Does the solution solve the original problem?
- What assumptions need verification?
- What's the simplest experiment to test this?
## Requirement Convergence Gate
Before final review, verify all of the following:
- the user outcome and product value are explicit
- in-scope and out-of-scope behavior are explicit
- acceptance criteria describe observable outcomes
- user-owned product, scope, UX, compatibility, and risk decisions are resolved
- blocking open questions are empty
- technical unknowns are researched or explicitly deferred without changing MVP behavior
Lightweight tasks may omit `design.md` and `implement.md`; they may not skip evidence inspection, requirement convergence, final review, or fresh implementation approval.
The final planning summary must show Goal, In Scope, Out of Scope, Acceptance Criteria, Key Decisions, relevant Risks or Deferred Items, and artifact status.
## Artifact Rules
`prd.md` records requirements and acceptance:
- goal and user value
- confirmed facts
- requirements
- acceptance criteria
- out of scope
- open questions that still block planning
`design.md` records technical design for complex tasks:
- architecture and boundaries
- data flow and contracts
- compatibility and migration notes
- important trade-offs
- operational or rollback considerations
`implement.md` records execution planning for complex tasks:
- ordered implementation checklist
- validation commands
- risky files or rollback points
- follow-up checks before `task.py start`
Lightweight tasks may have only `prd.md`. Complex tasks must have `prd.md`, `design.md`, and `implement.md` before `task.py start`.
`implement.md` is not a replacement for `implement.jsonl`. On sub-agent-dispatch workflows, `implement.jsonl` and `check.jsonl` must each contain at least one real spec/research entry before `task.py start`; an empty manifest, or one holding only a legacy `_example` placeholder row, does not count. Inline workflows skip this JSONL gate because Phase 2 loads context through `trellis-before-dev`.
## PRD Convergence Pass
Before declaring planning ready or running `task.py start`, rewrite `prd.md` once against the final structure described in the artifact rules above. This is not optional cleanup; it is the final planning gate.
The pass must be lossless:
- Collapse repeated facts into one authoritative section.
- Fold temporary brainstorm sections such as `What I already know`, `Assumptions`, and resolved `Open Questions` into Goal, Background, Requirements, Technical Notes, or Acceptance Criteria.
- Remove resolved open questions instead of leaving empty or already-answered sections.
- Merge parallel bug and requirement lists when they describe the same work; keep each defect's severity, evidence, and file:line anchors on the owning requirement.
- Preserve every file:line anchor, decision, constraint, requirement ID, and acceptance-criteria mapping.
- Do not proceed to final review while any blocking open question remains.
After the pass, read `prd.md` top to bottom and verify that no fact is repeated across sections unless the repetition adds new information.
## Quality Bar
Before declaring planning ready:
- `prd.md` contains testable acceptance criteria.
- `prd.md` has passed the PRD convergence pass: no unresolved temporary brainstorm sections, no duplicate facts across sections, and no lost anchors, decisions, or acceptance mappings.
- Repository-answerable questions have already been answered through inspection.
- Blocking open questions are empty.
- Complex tasks have `design.md` and `implement.md`.
- Sub-agent-dispatch tasks have real curated entries in both `implement.jsonl` and `check.jsonl`; seed-only manifests are not ready.
- The latest final planning summary has been presented to the user.
- The user explicitly approved this scope for implementation; unchanged restatements and clerical backfill do not invalidate that approval.
Do not start implementation merely because the user originally asked for implementation.
Present a concise plan with material risks and completion criteria. A recorded approval or explicit delegation covering this scope remains valid; clerical updates do not restart approval. Once required artifacts and decisions are complete, run the official `task.py start` command and continue approved implementation and checks. Reconfirm only material scope, risk or acceptance changes and separately protected operations.
+8 -178
查看文件
@@ -1,188 +1,18 @@
---
name: trellis-break-loop
description: "Deep bug analysis to break the fix-forget-repeat cycle. Analyzes root cause category, why fixes failed, prevention mechanisms, and captures knowledge into specs. Use after fixing a bug to prevent the same class of bugs."
description: "Analyze recurring bugs or failed fixes to identify a supported cause and targeted prevention; use for a requested debugging retrospective."
---
# Break the Loop - Deep Bug Analysis
# Learn From A Debugging Loop
When debug is complete, use this for deep analysis to break the "fix bug -> forget -> repeat" cycle.
Use the current task's evidence and existing analysis. An ordinary fix with adequate regression coverage does not automatically need a separate retrospective or new spec section.
---
Distinguish the observed failure, supported cause and remaining hypotheses. Explain earlier failed fixes only when they change the diagnosis. Consider missing contracts, cross-layer mismatch, missed consumers, inadequate coverage or an implicit assumption; these are prompts, not mandatory categories.
## Analysis Framework
When causes compete, choose a small check whose outcome distinguishes them. Preserve counterevidence, input/environment differences and failed runs. Do not invent numerical priors or confidence thresholds, or call a plausible explanation proven. Stop expanding the investigation when the authorized problem and meaningful regression are covered; new risks become scoped follow-up work.
Analyze the bug you just fixed from these 5 dimensions:
Choose the smallest useful prevention: correct the shared contract, add a behavioral regression, enforce an invariant or improve a specific diagnostic. Reuse existing protections. Similar symptoms warrant a targeted consumer check, not automatic repository-wide cleanup or a new abstraction.
### 1. Root Cause Category
Keep run chronology and unresolved hypotheses in the current task. Use `trellis-update-spec` only for a new, reusable lesson, updating its existing owner rather than duplicating it across spec and guides. Summarize cause, evidence, prevention and remaining limitations at the depth the problem needs.
Which category does this bug belong to?
| Category | Characteristics | Example |
|----------|-----------------|---------|
| **A. Missing Spec** | No documentation on how to do it | New feature without checklist |
| **B. Cross-Layer Contract** | Interface between layers unclear | API returns different format than expected |
| **C. Change Propagation Failure** | Changed one place, missed others | Changed function signature, missed call sites |
| **D. Test Coverage Gap** | Unit test passes, integration fails | Works alone, breaks when combined |
| **E. Implicit Assumption** | Code relies on undocumented assumption | Timestamp seconds vs milliseconds |
### 2. Why Fixes Failed (if applicable)
If you tried multiple fixes before succeeding, analyze each failure:
- **Surface Fix**: Fixed symptom, not root cause
- **Incomplete Scope**: Found root cause, didn't cover all cases
- **Tool Limitation**: grep missed it, type check wasn't strict
- **Mental Model**: Kept looking in same layer, didn't think cross-layer
### 3. Prevention Mechanisms
What mechanisms would prevent this from happening again?
| Type | Description | Example |
|------|-------------|---------|
| **Documentation** | Write it down so people know | Update thinking guide |
| **Architecture** | Make the error impossible structurally | Type-safe wrappers |
| **Compile-time** | Strict type checking, no escape hatches | Signature change causes compile error |
| **Runtime** | Monitoring, alerts, scans | Detect orphan entities |
| **Test Coverage** | E2E tests, integration tests | Verify full flow |
| **Code Review** | Checklist, PR template | "Did you check X?" |
### 4. Systematic Expansion
What broader problems does this bug reveal?
- **Similar Issues**: Where else might this problem exist?
- **Design Flaw**: Is there a fundamental architecture issue?
- **Process Flaw**: Is there a development process improvement?
- **Knowledge Gap**: Is the team missing some understanding?
### 5. Knowledge Capture
Solidify insights into the system:
- [ ] Update `.trellis/spec/guides/` thinking guides
- [ ] Update relevant `.trellis/spec/` docs
- [ ] Create issue record (if applicable)
- [ ] Create feature ticket for root fix
- [ ] Update check guidelines if needed
---
## Output Format
Please output analysis in this format:
```markdown
## Bug Analysis: [Short Description]
### 1. Root Cause Category
- **Category**: [A/B/C/D/E] - [Category Name]
- **Specific Cause**: [Detailed description]
### 2. Why Fixes Failed (if applicable)
1. [First attempt]: [Why it failed]
2. [Second attempt]: [Why it failed]
...
### 3. Prevention Mechanisms
| Priority | Mechanism | Specific Action | Status |
|----------|-----------|-----------------|--------|
| P0 | ... | ... | TODO/DONE |
### 4. Systematic Expansion
- **Similar Issues**: [List places with similar problems]
- **Design Improvement**: [Architecture-level suggestions]
- **Process Improvement**: [Development process suggestions]
### 5. Knowledge Capture
- [ ] [Documents to update / tickets to create]
```
---
## Core Philosophy
> **The value of debugging is not in fixing the bug, but in making this class of bugs never happen again.**
Three levels of insight:
1. **Tactical**: How to fix THIS bug
2. **Strategic**: How to prevent THIS CLASS of bugs
3. **Philosophical**: How to expand thinking patterns
30 minutes of analysis saves 30 hours of future debugging.
## Thinking Framework: Bayesian Reasoning
When multiple root causes are plausible and evidence is incomplete, update your beliefs proportionally to new evidence rather than clinging to initial assumptions.
### Step 1: Establish Priors
Before investigating, state what you believe and why:
| Hypothesis | Prior | Reasoning |
|------------|-------|-----------|
| H1: [cause A] | 40% | Most common for this pattern |
| H2: [cause B] | 30% | Plausible given environment |
| H3: [other] | 30% | Catch-all |
Priors must sum to 100%. If you can't assign probabilities, investigate first.
### Step 2: Observe Evidence
Document what you found — be specific about reliability:
- What exactly did you observe?
- How reliable? (test output > log message > user report > hunch)
- Could multiple hypotheses explain this?
### Step 3: Update Beliefs
For each hypothesis, ask: **How likely is this evidence if this hypothesis were true?**
Direction of update matters more than calculation:
- Evidence strongly predicted by H1 → H1 probability increases
- Evidence contradicts H2 → H2 probability decreases
- Evidence equally likely under all → no update
### Step 4: Seek Discriminating Evidence
Don't gather more of the same. Find evidence that **differs strongly** between top hypotheses.
> If H1 and H3 are close: "What would I see if H1 is true but not if H3 is true?" Then check for that.
### Step 5: State Confidence
| Confidence | Action |
|------------|--------|
| 90%+ | Proceed with fix, monitor |
| 70-90% | Proceed, add fallback check |
| 50-70% | Test hypothesis before committing |
| <50% | Need more evidence, don't guess |
Never express binary certainty when evidence is incomplete. Use "most likely", "plausible but unlikely", "worth investigating".
### Common Fallacies
| Fallacy | Example | Correction |
|---------|---------|------------|
| **Base rate neglect** | "Test failed → code is broken" | How often do tests fail for other reasons? |
| **Confirmation bias** | "Must be a race condition, let me find race evidence" | Actively seek evidence AGAINST your top hypothesis |
| **Anchoring** | "Last time it was caching, probably caching again" | Establish priors from current context, not yesterday's bug |
---
## After Analysis: Immediate Actions
**IMPORTANT**: After completing the analysis above, you MUST immediately:
1. **Update spec/guides** - Don't just list TODOs, actually update the relevant files:
- If it's a cross-platform issue → update `cross-platform-thinking-guide.md`
- If it's a cross-layer issue → update `cross-layer-thinking-guide.md`
- If it's a code reuse issue → update `code-reuse-thinking-guide.md`
- If it's domain-specific → update `backend/*.md` or `frontend/*.md`
2. **Sync templates** - After updating `.trellis/spec/`, sync to `src/templates/markdown/spec/`
3. **Commit the spec updates** - This is the primary output, not just the analysis text
> **The analysis is worthless if it stays in chat. The value is in the updated specs.**
Retrospective work does not authorize commits, archival, deployment, real-data operations or edits to an upstream template repository. Preserve project approval and independent-review requirements.
+6 -55
查看文件
@@ -1,61 +1,12 @@
---
name: trellis-continue
description: "Resume work on the current task. Loads the workflow Phase Index, figures out which phase/step to pick up at, then pulls the step-level detail via get_context.py --mode phase. Use when coming back to an in-progress task and you need to know what to do next."
description: "Resume an existing Trellis task after a pause or handoff; locate its current phase and next unfinished step."
---
# Continue Current Task
Resume work on the current task — pick up at the right phase/step in `.trellis/workflow.md`.
---
## Step 1: Load Current Context
```bash
python3 ./.trellis/scripts/get_context.py
```
Confirms: current task, git state, recent commits.
## Step 2: Load the Phase Index
```bash
python3 ./.trellis/scripts/get_context.py --mode phase
```
Shows the Phase Index (Plan / Execute / Finish) with routing + skill mapping.
## Step 3: Decide Where You Are
`get_context.py` shows the active task's `status` field. Route by `status` + artifact presence. This command replaces the user needing to remember the Trellis flow; it does not itself approve implementation.
- `status=planning` + no `prd.md` → **1.1** (load `trellis-brainstorm`)
- `status=planning` + `prd.md` only → decide whether the task is lightweight or complex. Lightweight can move to **1.4** review; complex returns to **1.1** to add `design.md` + `implement.md`.
- `status=planning` + complex artifacts complete + sub-agent jsonl not curated (empty, or only a legacy `_example` placeholder row) → **1.3**
- `status=planning` + required artifacts complete + required jsonl curated or inline mode → **1.4** (ask for start review; only run `task.py start` after user confirms)
- `status=in_progress` + implementation not started → **2.1**
- `status=in_progress` + implementation done, not yet checked → **2.2**
- `status=in_progress` + check passed → **3.3** (spec update) → **3.4** (commit)
- `status=completed` (rare; usually archived immediately) → archive flow
Phase rules (full detail in `.trellis/workflow.md`):
1. Run steps **in order** within a phase — `[required]` steps must not be skipped
2. `[once]` steps are already done if the required output exists. `prd.md` alone can be enough only for lightweight tasks; complex tasks also need `design.md` and `implement.md`.
3. You may go back to an earlier phase if discoveries require it
## Step 4: Load the Specific Step
Once you know which step to resume at:
```bash
python3 ./.trellis/scripts/get_context.py --mode phase --step <X.X> --platform codex
```
Follow the loaded instructions. After each `[required]` step completes, move to the next.
---
## Reference
Full workflow and detailed phase steps live in `.trellis/workflow.md`. This command is only an entry point — the canonical guidance is there.
1. Reuse fresh task context; otherwise run `python3 .trellis/scripts/task.py current --source` and read that task's `task.json`. If the pointer is missing, inspect directly related tasks before creating anything. Never infer another session's ownership. Use full `get_context.py` only for a broader session-state question.
2. Read the current PRD and the latest status/unfinished steps in `implement.md`; read the applicable design decisions when needed. Preserve constraints and approvals from the handoff. Do not reload unchanged history, unrelated journals or every spec.
3. Load the Phase Index only when routing is unclear: `python3 .trellis/scripts/get_context.py --mode phase`. Load the next step with `--mode phase --step <X.X> --platform codex`; the workflow owns phase rules, so do not maintain a duplicate routing table here.
4. Complete missing planning decisions before implementation. An existing PRD is not approval; recorded approval for unchanged scope permits `task.py start` and continued execution without another confirmation. Complex tasks need PRD, design and implementation notes; inline mode permits empty context manifests.
5. Use `trellis-before-dev` for implementation and `trellis-check` for verification. Continue through the approved scope and relevant checks; leave independent review explicitly pending if unavailable. Commit, push, archive, deployment and real-data operations retain their separate authorization boundaries.
@@ -11,7 +11,7 @@ It is intentionally a **capability skill, not a workflow**. There is no fixed ou
## What `trellis mem` is
A local CLI that indexes the user's past Claude Code, Codex, Pi Agent, and ZCode conversation logs and lets you list, search, slice by Trellis task boundaries, and dump cleaned dialogue from them. Claude and Codex use `~/.claude/projects/` and `~/.codex/sessions/`. Pi uses its default or environment-configured session root, global `~/.pi/agent/settings.json`, and the scoped project's `.pi/settings.json`; relative `sessionDir` values resolve from the settings file directory. Project-local Pi settings require project-scoped lookup through the current cwd or `--cwd`. ZCode uses `~/.zcode/cli/db/db.sqlite`. OpenCode logs are not yet indexable (provider adapter pending) — when an OpenCode session is the obvious target, surface that limitation rather than guessing.
A local CLI that indexes the user's past Claude Code, Codex, Devin CLI, Grok, OpenCode, Pi Agent, and ZCode conversation logs and lets you list, search, slice by Trellis task boundaries, and dump cleaned dialogue from them. Claude and Codex use `~/.claude/projects/` and `~/.codex/sessions/`. Devin CLI (Cognition terminal agent, not `trellis init --devin` Desktop) uses `~/.local/share/devin/cli/sessions.db`. Grok uses `~/.grok/sessions/`. OpenCode uses `~/.local/share/opencode/opencode.db` (zero-dependency SQLite reader). Pi uses its default or environment-configured session root, global `~/.pi/agent/settings.json`, and the scoped project's `.pi/settings.json`; relative `sessionDir` values resolve from the settings file directory. Project-local Pi settings require project-scoped lookup through the current cwd or `--cwd`. ZCode uses `~/.zcode/cli/db/db.sqlite`.
Nothing in `mem` is uploaded. All reads are local.
@@ -16,7 +16,7 @@ Full flag reference for the five subcommands. Pin this as the authoritative sour
| Flag | Subcommands | Meaning |
| --------------------------------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--platform claude\|codex\|opencode\|pi\|all` | all | Default `all`. OpenCode adapter is currently a stub on `0.6.0-beta.*` — see "Caveats" below. |
| `--platform claude\|codex\|devin\|grok\|opencode\|pi\|zcode\|all` | all | Default `all`. `devin` is Cognition Devin CLI (`sessions.db`), not `trellis init --devin` (Desktop). |
| `--since YYYY-MM-DD` | list / search | Inclusive lower date bound. |
| `--until YYYY-MM-DD` | list / search | Inclusive upper date bound. |
| `--global` | list / search | Include sessions from every project on this machine. Default is the current project `cwd`. |
@@ -56,6 +56,7 @@ trellis mem projects
## Caveats
- **OpenCode adapter is a stub on `0.6.0-beta.*`.** When `--platform` resolves to OpenCode (or `all` and OpenCode would be included), `mem` prints a one-line "reader unavailable" notice and continues with the other platforms. Don't promise OpenCode coverage in your reply until the adapter ships.
- **`--platform devin` is Cognition Devin CLI** (`~/.local/share/devin/cli/sessions.db`). It is not `trellis init --devin` (Devin Desktop / Cascade) and not Factory Droid.
- **`--phase` slicing depends on `task.py create` / `task.py start` invocations appearing in the recorded bash calls of the session.** Sessions where the user ran `task.py` from a different terminal — outside the recorded AI loop — will not have phase boundaries. `--phase all` is the safe fallback.
- **`mem` indexes platform JSONL files directly.** If the user has cleared their Claude / Codex / Pi session storage, `mem` cannot recover what is no longer on disk.
- **`mem` is read-only.** No remote sync, no edits to platform JSONL. Any write you do based on `mem` findings is your own follow-up call into the editing tools available to you.
+6 -6
查看文件
@@ -5,10 +5,10 @@ description: "Initialize or resume non-trivial work in this Trellis project. Ski
# Start Session
1. Classify the request before loading context. Pure consultation and small isolated edits do not need a task or a task-creation question. Preserve risk boundaries in AGENTS.md.
2. For tracked work, obtain current task and status from already supplied context, or run get_context.py when missing or stale. Do not enumerate unrelated journals and historical tasks.
3. Read the workflow Phase Index and current step on demand. Read the current PRD, then design and implementation notes if needed. Reuse unchanged material already loaded in this session.
4. With no task, obtain task-creation consent for non-trivial work unless already authorized. With a planning task, complete missing decisions; once its plan is approved, start and execute without asking again. An existing PRD alone is not proof of approval.
5. For implementation load trellis-before-dev; for verification load trellis-check. Load spec indexes only for affected layers and follow relevant links, not every guideline.
1. Classify the request. Pure consultation and small isolated edits need no task unless requested; preserve AGENTS.md risk boundaries.
2. Reuse fresh task context; otherwise run `python3 .trellis/scripts/task.py current --source` and read its status. If no pointer exists, inspect directly related tasks before creating one. Use full `get_context.py` only for broader session state.
3. Load the workflow Phase Index/current step and task PRD as needed, then relevant design/implementation notes. Reuse unchanged material.
4. Obtain creation/plan approval only when missing. A PRD alone is not approval; an approved unchanged plan permits start and execution without asking again.
5. Load `trellis-before-dev` for implementation and `trellis-check` for verification. Follow affected-layer references, not every guide. Missing optional tools use supported fallbacks, not repeated permission requests.
The project workflow and task status are authoritative over legacy user-level Trellis skills. Missing optional tools require a supported fallback or a precise limitation report, not repeated permission requests.
Project workflow and task status take precedence over legacy user-level Trellis skills.
+11 -346
查看文件
@@ -1,356 +1,21 @@
---
name: trellis-update-spec
description: "Captures executable contracts and coding conventions into .trellis/spec/ documents. Use when learning something valuable from debugging, implementing, or discussion that should be preserved for future sessions."
description: "Maintain an existing spec when a verified change reveals a reusable contract, convention or pitfall; exclude routine status and run logs."
---
# Update Code-Spec - Capture Executable Contracts
# Maintain Reusable Contracts
When you learn something valuable (from debugging, implementing, or discussion), use this to update the relevant code-spec documents.
First decide whether there is a new, supported lesson worth retaining. No spec edit is needed when the contract is already documented, evidence is inconclusive or the fact belongs only to this run. Model upgrades alone are not evidence that a business safeguard is obsolete.
**Timing**: After completing a task, fixing a bug, or discovering a new pattern
Use the package index and heading search to locate the owning section. Read its applicable contract and references before editing. Update or consolidate that section; create a new one only for a distinct concept. Keep business facts in the existing docs owner, executable development rules in spec, and thinking prompts in guides that point to those rules. Do not replicate the same contract in each layer.
---
Preserve concrete depth when commands/APIs, schemas, infrastructure or cross-layer behavior change:
- Applicable scope and the actual signature, fields/types, storage or configuration keys.
- Required invariants, validation/authorization boundaries, failure behavior and compatibility or migration constraints.
- The observable assertions and relevant test commands that distinguish correct behavior from the failure.
## Code-Spec First Rule (CRITICAL)
Use the shortest clear structure: a paragraph, table or focused example is often enough. A good/bad example helps when it explains a subtle distinction; it is not required for every lesson. Follow any explicitly required task/delivery format, but do not impose seven sections, a code sample or a new document on every change.
In this project, "spec" for implementation work means **code-spec**:
- Executable contracts (not principle-only text)
- Concrete signatures, payload fields, env keys, and boundary behavior
- Testable validation/error behavior
Before removing material, inspect its callers/references and preserve unique conditions, exceptions, evidence links and requirement IDs. Retire stale instructions only after confirming the current owner and scope. Historical findings, run counts, timestamps, candidate hashes, approvals and original receipts remain in task/evidence; a new result must not rewrite their past state.
If the change touches infra or cross-layer contracts, code-spec depth is mandatory.
### Mandatory Triggers
Apply code-spec depth when the change includes any of:
- New/changed command or API signature
- Cross-layer request/response contract change
- Database schema/migration change
- Infra integration (storage, queue, cache, secrets, env wiring)
### Mandatory Output (7 Sections)
For triggered tasks, include all sections below:
1. Scope / Trigger
2. Signatures (command/API/DB)
3. Contracts (request/response/env)
4. Validation & Error Matrix
5. Good/Base/Bad Cases
6. Tests Required (with assertion points)
7. Wrong vs Correct (at least one pair)
---
## When to Update Code-Specs
| Trigger | Example | Target Spec |
|---------|---------|-------------|
| **Implemented a feature** | Added a new integration or module | Relevant spec file |
| **Made a design decision** | Chose extensibility pattern over simplicity | Relevant spec + "Design Decisions" section |
| **Fixed a bug** | Found a subtle issue with error handling | Relevant spec (e.g., error-handling docs) |
| **Discovered a pattern** | Found a better way to structure code | Relevant spec file |
| **Hit a gotcha** | Learned that X must be done before Y | Relevant spec + "Common Mistakes" section |
| **Established a convention** | Team agreed on naming pattern | Quality guidelines |
| **New thinking trigger** | "Don't forget to check X before doing Y" | `guides/*.md` (as a checklist item) |
**Key Insight**: Code-spec updates are NOT just for problems. Every feature implementation contains design decisions and contracts that future AI/developers need to execute safely.
---
## Spec Structure Overview
```
.trellis/spec/
├── <layer>/ # Per-layer coding standards (e.g., backend/, frontend/, api/)
│ ├── index.md # Overview and links
│ └── *.md # Topic-specific guidelines
└── guides/ # Thinking checklists (NOT coding specs!)
├── index.md # Guide index
└── *.md # Topic-specific guides
```
### CRITICAL: Code-Spec vs Guide - Know the Difference
| Type | Location | Purpose | Content Style |
|------|----------|---------|---------------|
| **Code-Spec** | `<layer>/*.md` | Tell AI "how to implement safely" | Signatures, contracts, matrices, cases, test points |
| **Guide** | `guides/*.md` | Help AI "what to think about" | Checklists, questions, pointers to specs |
**Decision Rule**: Ask yourself:
- "This is **how to write** the code" → Put in a spec layer directory
- "This is **what to consider** before writing" → Put in `guides/`
**Example**:
| Learning | Wrong Location | Correct Location |
|----------|----------------|------------------|
| "Use API X not API Y for this task" | ❌ `guides/` (too specific for a thinking guide) | ✅ Relevant spec file (concrete convention) |
| "Remember to check X when doing Y" | ❌ Spec file (too abstract for a spec) | ✅ `guides/` (thinking checklist) |
**Guides should be short checklists that point to specs**, not duplicate the detailed rules.
---
## Update Process
### Step 1: Identify What You Learned
Answer these questions:
1. **What did you learn?** (Be specific)
2. **Why is it important?** (What problem does it prevent?)
3. **Where does it belong?** (Which spec file?)
### Step 2: Classify the Update Type
| Type | Description | Action |
|------|-------------|--------|
| **Design Decision** | Why we chose approach X over Y | Add to "Design Decisions" section |
| **Project Convention** | How we do X in this project | Add to relevant section with examples |
| **New Pattern** | A reusable approach discovered | Add to "Patterns" section |
| **Forbidden Pattern** | Something that causes problems | Add to "Anti-patterns" or "Don't" section |
| **Common Mistake** | Easy-to-make error | Add to "Common Mistakes" section |
| **Convention** | Agreed-upon standard | Add to relevant section |
| **Gotcha** | Non-obvious behavior | Add warning callout |
### Step 3: Read the Target Code-Spec
Before editing, read the current code-spec to:
- Understand existing structure
- Avoid duplicating content
- Find the right section for your update
```bash
cat .trellis/spec/<category>/<file>.md
```
### Step 4: Make the Update
Follow these principles:
1. **Be Specific**: Include concrete examples, not just abstract rules
2. **Explain Why**: State the problem this prevents
3. **Show Contracts**: Add signatures, payload fields, and error behavior
4. **Show Code**: Add code snippets for key patterns
5. **Keep it Short**: One concept per section
### Step 5: Update the Index (if needed)
If you added a new section or the code-spec status changed, update the category's `index.md`.
---
## Update Templates
### Mandatory Template for Infra/Cross-Layer Work
```markdown
## Scenario: <name>
### 1. Scope / Trigger
- Trigger: <why this requires code-spec depth>
### 2. Signatures
- Backend command/API/DB signature(s)
### 3. Contracts
- Request fields (name, type, constraints)
- Response fields (name, type, constraints)
- Environment keys (required/optional)
### 4. Validation & Error Matrix
- <condition> -> <error>
### 5. Good/Base/Bad Cases
- Good: ...
- Base: ...
- Bad: ...
### 6. Tests Required
- Unit/Integration/E2E with assertion points
### 7. Wrong vs Correct
#### Wrong
...
#### Correct
...
```
### Adding a Design Decision
```markdown
### Design Decision: [Decision Name]
**Context**: What problem were we solving?
**Options Considered**:
1. Option A - brief description
2. Option B - brief description
**Decision**: We chose Option X because...
**Example**:
\`\`\`typescript
// How it's implemented
code example
\`\`\`
**Extensibility**: How to extend this in the future...
```
### Adding a Project Convention
```markdown
### Convention: [Convention Name]
**What**: Brief description of the convention.
**Why**: Why we do it this way in this project.
**Example**:
\`\`\`typescript
// How to follow this convention
code example
\`\`\`
**Related**: Links to related conventions or specs.
```
### Adding a New Pattern
```markdown
### Pattern Name
**Problem**: What problem does this solve?
**Solution**: Brief description of the approach.
**Example**:
\`\`\`
// Good
code example
// Bad
code example
\`\`\`
**Why**: Explanation of why this works better.
```
### Adding a Forbidden Pattern
```markdown
### Don't: Pattern Name
**Problem**:
\`\`\`
// Don't do this
bad code example
\`\`\`
**Why it's bad**: Explanation of the issue.
**Instead**:
\`\`\`
// Do this instead
good code example
\`\`\`
```
### Adding a Common Mistake
```markdown
### Common Mistake: Description
**Symptom**: What goes wrong
**Cause**: Why this happens
**Fix**: How to correct it
**Prevention**: How to avoid it in the future
```
### Adding a Gotcha
```markdown
> **Warning**: Brief description of the non-obvious behavior.
>
> Details about when this happens and how to handle it.
```
---
## Interactive Mode
If you're unsure what to update, answer these prompts:
1. **What did you just finish?**
- [ ] Fixed a bug
- [ ] Implemented a feature
- [ ] Refactored code
- [ ] Had a discussion about approach
2. **What did you learn or decide?**
- Design decision (why X over Y)
- Project convention (how we do X)
- Non-obvious behavior (gotcha)
- Better approach (pattern)
3. **Would future AI/developers need to know this?**
- To understand how the code works → Yes, update spec
- To maintain or extend the feature → Yes, update spec
- To avoid repeating mistakes → Yes, update spec
- Purely one-off implementation detail → Maybe skip
4. **Which area does it relate to?**
- [ ] Backend code
- [ ] Frontend code
- [ ] Cross-layer data flow
- [ ] Code organization/reuse
- [ ] Quality/testing
---
## Quality Checklist
Before finishing your code-spec update:
- [ ] Is the content specific and actionable?
- [ ] Did you include a code example?
- [ ] Did you explain WHY, not just WHAT?
- [ ] Did you include executable signatures/contracts?
- [ ] Did you include validation and error matrix?
- [ ] Did you include Good/Base/Bad cases?
- [ ] Did you include required tests with assertion points?
- [ ] Is it in the right code-spec file?
- [ ] Does it duplicate existing content?
- [ ] Would a new team member understand it?
---
## Relationship to Other Commands
```
Development Flow:
Learn something → `update-spec` (Trellis command) → Knowledge captured
↑ ↓
`break-loop` (Trellis command) ←──────────────────── Future sessions benefit
(deep bug analysis)
```
- ``break-loop` (Trellis command)` - Analyzes bugs deeply, often reveals spec updates needed
- ``update-spec` (Trellis command)` - Actually makes the updates
- ``finish-work` (Trellis command)` - Reminds you to check if specs need updates
---
## Core Philosophy
> **Code-specs are living documents. Every debugging session, every "aha moment" is an opportunity to make the implementation contract clearer.**
The goal is **institutional memory**:
- What one person learns, everyone benefits from
- What AI learns in one session, persists to future sessions
- Mistakes become documented guardrails
Check links and affected process/doc contracts. Reuse unchanged test results; rerun relevant checks when behavior or inputs changed. Update an index only if discovery or ownership changed. Report the actual maintenance scope and limitations. Do not auto-commit, archive, alter runtime templates/hashes, or modify upstream/global files as a side effect.