Core logic for dex knowledge capture: project discovery, document formats, CLAUDE.md budget management, and promotion flow. Referenced by all dex commands.
Shared logic for all /dex:* commands. Follow these procedures exactly — do what the calling command asks, nothing more.
Discover the project's knowledge infrastructure fresh on every invocation. Scan the filesystem directly — no config files, no cached state.
git rev-parse --show-toplevel<root>/CLAUDE.md<root>/.claude/CLAUDE.md<root>/AGENTS.md — a direct AGENTS.md project (e.g. a Codex-only repo
with no CLAUDE.md). Use it as the instructions file with ai_dir = .ai,
then skip the CLAUDE.md indirection in step 3a.ai_dir:
a. If a CLAUDE.md was found, check whether it redirects to AGENTS.md:
readlink <claude_md_path>. If the target filename is AGENTS.md, use the symlink target.@AGENTS.md line (with optional whitespace/newlines), find the referenced AGENTS.md relative to CLAUDE.md's directory.ai_dir from the resolved instructions file:ai_dir = .claudeai_dir = .ai<root>/<ai_dir>/docs/
ai_dir is .ai but <root>/.ai/docs/ does not exist and <root>/.claude/docs/ does exist, flag a migration mismatch. Use .claude/docs/ as the active knowledge directory for now, but record the mismatch for init and status to surface.learnings/, patterns/, decisions/, research/ within the knowledge directorywc -l on the resolved instructions fileIf a CLAUDE.md or .claude/docs/ does not exist, proceed with what you have. Missing infrastructure is a normal state — handle it per the calling command's instructions.
Build this mental model before proceeding:
project_root: /path/to/project
instructions_file: /path/to/project/CLAUDE.md (387 lines)
ai_dir: .claude
knowledge_dir: /path/to/project/.claude/docs/
learnings: exists (7 files)
patterns: exists (3 files)
decisions: exists (2 files)
research: exists (1 file)
If AGENTS.md indirection was resolved:
project_root: /path/to/project
instructions_file: /path/to/project/AGENTS.md (387 lines, resolved from CLAUDE.md)
ai_dir: .ai
knowledge_dir: /path/to/project/.ai/docs/
learnings: exists (7 files)
patterns: exists (3 files)
decisions: exists (2 files)
research: exists (1 file)
If migration mismatch was detected (AGENTS.md + existing .claude/docs/):
project_root: /path/to/project
instructions_file: /path/to/project/AGENTS.md (387 lines, resolved from CLAUDE.md)
ai_dir: .ai
knowledge_dir: /path/to/project/.claude/docs/ (migration available → .ai/docs/)
learnings: exists (7 files)
patterns: exists (3 files)
decisions: exists (2 files)
research: exists (1 file)
Throughout this skill and all /dex:* commands:
.claude/ and .claude/docs/ refer to the resolved ai_dir (<ai_dir>/ and <ai_dir>/docs/)Substitute the resolved values in all paths and user-facing messages. For example, when ai_dir is .ai: "Promote to AGENTS.md?", "Create .ai/docs/?", scaffolding creates .ai/docs/learnings/ etc.
If .claude/docs/ doesn't exist, commands should ask the user whether to
scaffold it using the current host's input mechanism before proceeding (except
/dex:status, which reports the absence).
When scaffolding is needed, create these directories:
.claude/docs/learnings/.claude/docs/patterns/.claude/docs/decisions/.claude/docs/research/Create empty directories only. No README files, no templates, no boilerplate.
All documents are agent-first: the first section contains the actionable directive — an AI agent reading only the Rule/Pattern/Decision section gets enough to act. Context and examples follow for depth.
These docs are consumed by AI agents, not read by humans. Every formatting choice must earn its tokens:
Details: path/to/file.md not [details](path/to/file.md). Agents don't click links.Date: 2026-02-13 not **Date:** 2026-02-13. Bold markers serve human eyes only.src/gateway.php:45 not "see the gateway file". Include line numbers when relevant.Use for: discoveries, fixes, gotchas, debugging insights, non-obvious behaviors.
# Short directive title
Date: YYYY-MM-DD
Tags: tag1, tag2, tag3
## Rule
The actionable directive — what to do or not do. An agent reading
only this section should know enough to apply the knowledge.
## Context
Why this matters. What went wrong or what was non-obvious.
Technical explanation of the root cause.
## Examples
Code examples showing correct and incorrect approaches.
Use CORRECT / WRONG labels for clarity.
<example type="CORRECT">
# Always pass --user=1 for WP-CLI REST calls with auth
Date: 2026-02-13 Tags: wp-cli, rest-api, authentication
Always pass --user=1 when making WP-CLI REST API calls that have
permission callbacks. Without it, the call runs as unauthenticated.
</example>
Today I discovered that WP-CLI REST API calls need authentication. This was really confusing and took a while to debug. The error was a 403... </example>
Use for: reusable approaches, conventions, anti-patterns, recurring solutions.
# Short pattern name
Date: YYYY-MM-DD
Tags: tag1, tag2, tag3
## Pattern
The reusable approach — what it is and how to apply it.
## When to apply
- Condition 1
- Condition 2
## Alternatives
- When [condition 1], prefer [alternative approach] instead
- When [condition 2], [simpler method] works better because [reason]
## Reference implementation
Direct file:line reference (e.g., `src/gateway.php:45-60`), or inline code example.
Use for: architectural choices, trade-off decisions, technology selections.
# Short decision statement
Date: YYYY-MM-DD
Tags: tag1, tag2, tag3
## Decision
What was chosen and the one-line rationale.
## Alternatives considered
- Option A: Description — why rejected
- Option B (chosen): Description — why chosen
- Option C: Description — why rejected
## Why this choice
Detailed reasoning, trade-offs, and constraints that led to this choice.
Use for: extensive investigations, multi-hour debugging sessions, API explorations, trial-and-error findings across environments.
# Short title describing what was researched
Date: YYYY-MM-DD
Tags: tag1, tag2, tag3
Environment: key versions, OS, configs that matter
Status: current
## Summary
2-3 sentence overview of key findings for quick scanning.
## What Works
Proven approaches with evidence (commands, configs, code).
## What Doesn't Work
Failed approaches and WHY they failed.
## Key Findings
Detailed empirical observations, numbered for reference.
## Reproduction Steps
How to verify or reproduce the findings.
## Open Questions
Unresolved issues or areas needing further investigation.
Key differences from Learning:
Environment field — versions, OS, configs for assessing relevance over timeStatus field — current / outdated / superseded for freshness trackingDate: 2026-02-15 Tags: php-8.3, readonly, woocommerce, hooks Environment: PHP 8.3.4, WooCommerce 9.6.0, WordPress 6.7 Status: current
PHP 8.3 readonly properties cannot be re-initialized after clone. WooCommerce hook callbacks that clone objects hit fatal errors with readonly properties.
Use backed enums or private properties with getters instead of readonly.
clone $order with readonly properties → Fatal errorToday I spent a few hours looking into PHP 8.3. I tried a bunch of things and some worked and some didn't. Here's what I found... </example>
All files follow: YYYY-MM-DD-slug.md
Slug rules:
digraph promotion_decision {
"Document captured" [shape=doublecircle];
"What type?" [shape=diamond];
"Always offer promotion" [shape=box];
"Meets promotion criteria?" [shape=diamond];
"Offer promotion" [shape=box];
"Skip silently" [shape=doublecircle];
"No promotion" [shape=doublecircle];
"Count CLAUDE.md lines" [shape=box];
"Lines < 500?" [shape=diamond];
"Promote freely" [shape=doublecircle];
"Lines 500-550?" [shape=diamond];
"Warn: near budget" [shape=box];
"STOP: Over budget — extract first" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
"Document captured" -> "What type?";
"What type?" -> "Always offer promotion" [label="Pattern"];
"What type?" -> "Meets promotion criteria?" [label="Learning"];
"What type?" -> "No promotion" [label="Decision/Research"];
"Meets promotion criteria?" -> "Offer promotion" [label="yes"];
"Meets promotion criteria?" -> "Skip silently" [label="no"];
"Always offer promotion" -> "Count CLAUDE.md lines";
"Offer promotion" -> "Count CLAUDE.md lines";
"Count CLAUDE.md lines" -> "Lines < 500?";
"Lines < 500?" -> "Promote freely" [label="yes"];
"Lines < 500?" -> "Lines 500-550?" [label="no"];
"Lines 500-550?" -> "Warn: near budget" [label="yes"];
"Lines 500-550?" -> "STOP: Over budget — extract first" [label="no"];
}
Graduation flow: /dex:grok may offer to upgrade a learning to a pattern when reusability signals are detected. Delegates to /dex:pattern for Alternatives and When to apply sections.
Learning promotion criteria — at least one:
Skip promotion silently for informational learnings, one-off debugging insights, decisions, and research.
Budget 500-550: Warn using the current host's input mechanism: "CLAUDE.md is at X/500 lines." Options: "Add anyway" / "Extract a section first"
Budget 550+: Hard block. Tell user to extract sections first. Show sections ranked by line count, offer to extract largest. Proceed only after extraction brings count below 550.
One-liner + bare path to the source document:
- Always pass `--user=1` for WP-CLI REST calls with auth. Details: .claude/docs/learnings/2026-02-13-wp-cli-rest-auth.md
<example type="CORRECT" label="bare path saves tokens">
- Always pass `--user=1` for WP-CLI REST calls with auth. Details: .claude/docs/learnings/2026-02-13-wp-cli-rest-auth.md
</example>
<example type="INCORRECT" label="redundant markdown link wastes tokens">
- Always pass `--user=1` for WP-CLI REST calls with auth. See [details](.claude/docs/learnings/2026-02-13-wp-cli-rest-auth.md).
</example>
When promoting a rule to CLAUDE.md:
## section headings## heading)When extracting a section from CLAUDE.md:
## sections with their line counts.claude/docs/ as a standalone doc## Section Name
Full details: .claude/docs/section-name.md
Before drafting, analyze the relevant conversation exchange:
<pre_extraction_analysis>
Then draft:
Focus on what an agent needs to act differently next time, not on narrating what happened during debugging.
Before saving any document, verify it passes all four checks. If any check fails, revise before saving.
<extraction_quality_checklist>
If writing a document file fails (permissions, disk full, invalid path), report the error and display the intended file path and full document content so the user can save it manually. Do not retry — the user may need to fix permissions or path issues first.
Shared logic for analyzing agent behavior in a conversation to find inefficiencies and capture fixes as project knowledge. Used by /dex:sharpen.
Scan the conversation for these categories of wasted effort:
| Category | What to look for |
|----------|-----------------|
| Wrong tool usage | Used Bash when Grep/Glob/Read was better; used find instead of Glob; used cat instead of Read |
| Inefficient discovery | Took 5+ searches to find something findable in 1-2; didn't use IDE index tools when available |
| Missed shortcuts | Didn't leverage existing project scripts, aliases, or conventions documented in CLAUDE.md |
| Rediscovering known info | Debugged something already documented in CLAUDE.md or .claude/docs/ |
| Incorrect assumptions | Assumed wrong file structure, API shape, or convention — then had to backtrack |
| Unnecessary confirmation loops | Asked the user things that could be inferred from context or existing docs |
| Over-broad scope | Read entire files when only a section was needed; searched too widely before narrowing |
Flag only inefficiencies that meet both criteria:
Skip: one-time wrong guesses, normal exploration overhead, reasonable first attempts that didn't pan out.
For each flagged inefficiency, note three things:
Map each identified inefficiency to its fix destination:
| Root cause | Output destination |
|-----------|-------------------|
| Missing rule (do/don't directive) | CLAUDE.md promotion candidate |
| Missing knowledge (debugging insight, gotcha) | .claude/docs/learnings/ |
| Missing approach (reusable workflow) | .claude/docs/patterns/ |
| Skill gap (agent needs better instructions) | .claude/docs/learnings/ tagged skill-improvement |
Apply the standard extraction quality checklist (self-contained, actionable, specific, concise) PLUS these three additional checks:
Agent-operational: tells the agent how to run commands in this project. Preventive: specifies what to do before making the call. Non-obvious: project-specific pnpm wrapper isn't discoverable without experience. </example>
<example type="INCORRECT" label="domain knowledge — use /dex:learn instead"> Rule: "The REST API returns 403 when permissions are missing"This is domain knowledge (how WordPress works), not operational knowledge
(how the agent should work). Capture via /dex:learn instead.
</example>
Running log at .claude/docs/.sharpen-log.md that tracks efficiency fixes across sessions. Used by /dex:sharpen to avoid duplicating previously captured knowledge.
# Sharpen Audit Log
## YYYY-MM-DD
- [category]: [1-sentence summary] → [file path]
- [category]: [1-sentence summary] → [file path]
Before analyzing, read .claude/docs/.sharpen-log.md if it exists. Compare previous findings against current conversation to skip inefficiencies already captured. If the log does not exist, proceed normally — it will be created after capture.
After capturing fixes, append a dated section to .claude/docs/.sharpen-log.md. Create the file if it does not exist. Each entry is one line per captured fix.
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer