knowns 0.8.8 → 0.9.0

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.
package/dist/index.js CHANGED
@@ -30454,7 +30454,7 @@ var require_view = __commonJS({
30454
30454
  var dirname5 = path.dirname;
30455
30455
  var basename3 = path.basename;
30456
30456
  var extname = path.extname;
30457
- var join24 = path.join;
30457
+ var join25 = path.join;
30458
30458
  var resolve = path.resolve;
30459
30459
  module2.exports = View;
30460
30460
  function View(name, options2) {
@@ -30516,12 +30516,12 @@ var require_view = __commonJS({
30516
30516
  };
30517
30517
  View.prototype.resolve = function resolve2(dir, file3) {
30518
30518
  var ext = this.ext;
30519
- var path2 = join24(dir, file3);
30519
+ var path2 = join25(dir, file3);
30520
30520
  var stat3 = tryStat(path2);
30521
30521
  if (stat3 && stat3.isFile()) {
30522
30522
  return path2;
30523
30523
  }
30524
- path2 = join24(dir, basename3(file3, ext), "index" + ext);
30524
+ path2 = join25(dir, basename3(file3, ext), "index" + ext);
30525
30525
  stat3 = tryStat(path2);
30526
30526
  if (stat3 && stat3.isFile()) {
30527
30527
  return path2;
@@ -34166,7 +34166,7 @@ var require_send = __commonJS({
34166
34166
  var Stream = __require("stream");
34167
34167
  var util2 = __require("util");
34168
34168
  var extname = path.extname;
34169
- var join24 = path.join;
34169
+ var join25 = path.join;
34170
34170
  var normalize = path.normalize;
34171
34171
  var resolve = path.resolve;
34172
34172
  var sep = path.sep;
@@ -34338,7 +34338,7 @@ var require_send = __commonJS({
34338
34338
  return res;
34339
34339
  }
34340
34340
  parts = path2.split(sep);
34341
- path2 = normalize(join24(root, path2));
34341
+ path2 = normalize(join25(root, path2));
34342
34342
  } else {
34343
34343
  if (UP_PATH_REGEXP.test(path2)) {
34344
34344
  debug('malicious path "%s"', path2);
@@ -34471,7 +34471,7 @@ var require_send = __commonJS({
34471
34471
  if (err) return self.onStatError(err);
34472
34472
  return self.error(404);
34473
34473
  }
34474
- var p = join24(path2, self._index[i]);
34474
+ var p = join25(path2, self._index[i]);
34475
34475
  debug('stat "%s"', p);
34476
34476
  fs.stat(p, function(err2, stat3) {
34477
34477
  if (err2) return next(err2);
@@ -43469,6 +43469,78 @@ var {
43469
43469
  // src/commands/init.ts
43470
43470
  var import_prompts2 = __toESM(require_prompts3(), 1);
43471
43471
 
43472
+ // src/templates/skills/knowns.commit/SKILL.md
43473
+ var SKILL_default = '---\nname: knowns.commit\ndescription: Use when committing code changes with proper conventional commit format and verification\n---\n\n# Committing Changes\n\nYour task is to help the user to generate a commit message and commit the changes using git.\n\n## Guidelines\n\n- DO NOT add any ads such as "Generated with [Claude Code](https://claude.ai/code)"\n- DO NOT add Co-Authored-By line\n- Only generate the message for staged files/changes\n- Don\'t add any files using `git add`. The user will decide what to add.\n- Follow the rules below for the commit message.\n\n## Format\n\n```\n<type>:<space><message title>\n\n<bullet points summarizing what was updated>\n```\n\n## Example Titles\n\n```\nfeat(auth): add JWT login flow\nfix(ui): handle null pointer in sidebar\nrefactor(api): split user controller logic\ndocs(readme): add usage section\n```\n\n## Example with Title and Body\n\n```\nfeat(auth): add JWT login flow\n\n- Implemented JWT token validation logic\n- Added documentation for the validation component\n```\n\n## Rules\n\n* Title is lowercase, no period at the end.\n* Title should be a clear summary, max 50 characters.\n* Use the body (optional) to explain *why*, not just *what*.\n* Bullet points should be concise and high-level.\n\n**Avoid:**\n* Vague titles like: "update", "fix stuff"\n* Overly long or unfocused titles\n* Excessive detail in bullet points\n\n## Allowed Types\n\n| Type | Description |\n| -------- | ------------------------------------- |\n| feat | New feature |\n| fix | Bug fix |\n| chore | Maintenance (e.g., tooling, deps) |\n| docs | Documentation changes |\n| refactor | Code restructure (no behavior change) |\n| test | Adding or refactoring tests |\n| style | Code formatting (no logic change) |\n| perf | Performance improvements |\n\n## Process\n\n1. Run `git status` and `git diff --staged` to see staged changes\n2. Generate commit message following the format above\n3. Show the message to user and ask for confirmation\n4. Commit with `git commit -m "message"`\n';
43474
+
43475
+ // src/templates/skills/knowns.doc/SKILL.md
43476
+ var SKILL_default2 = '---\nname: knowns.doc\ndescription: Use when working with Knowns documentation - viewing, searching, creating, or updating docs\n---\n\n# Working with Documentation\n\nNavigate, create, and update Knowns project documentation.\n\n**Announce at start:** "I\'m using the knowns.doc skill to work with documentation."\n\n**Core principle:** SEARCH BEFORE CREATING - avoid duplicates.\n\n## Quick Reference\n\n```bash\n# List all docs\nknowns doc list --plain\n\n# View doc (auto-handles large docs)\nknowns doc "<path>" --plain --smart\n\n# Search docs\nknowns search "<query>" --type doc --plain\n\n# Create doc\nknowns doc create "<title>" -d "<description>" -t "tags" -f "folder"\n\n# Update doc\nknowns doc edit "<path>" -c "content" # Replace\nknowns doc edit "<path>" -a "content" # Append\nknowns doc edit "<path>" --section "2" -c "content" # Section only\n```\n\n## Reading Documents\n\n**Always use `--smart` flag:**\n\n```bash\nknowns doc "<path>" --plain --smart\n```\n\n- Small doc (\u22642000 tokens) \u2192 full content\n- Large doc \u2192 stats + TOC, then use `--section`\n\n## Creating Documents\n\n### Step 1: Search First\n\n```bash\nknowns search "<topic>" --type doc --plain\n```\n\n**Don\'t duplicate.** Update existing docs when possible.\n\n### Step 2: Choose Location\n\n| Doc Type | Location | Flag |\n|----------|----------|------|\n| Core (README, ARCH) | Root | No `-f` |\n| Guide | `guides/` | `-f "guides"` |\n| Pattern | `patterns/` | `-f "patterns"` |\n| API doc | `api/` | `-f "api"` |\n\n### Step 3: Create\n\n```bash\nknowns doc create "<title>" \\\n -d "<brief description>" \\\n -t "tag1,tag2" \\\n -f "folder" # optional\n```\n\n### Step 4: Add Content\n\n```bash\nknowns doc edit "<path>" -c "$(cat <<\'EOF\'\n# Title\n\n## 1. Overview\nWhat this doc covers.\n\n## 2. Details\nMain content.\n\n## 3. Examples\nPractical examples.\nEOF\n)"\n```\n\n## Updating Documents\n\n### View First\n\n```bash\nknowns doc "<path>" --plain --smart\nknowns doc "<path>" --toc --plain # For large docs\n```\n\n### Update Methods\n\n| Method | Command | Use When |\n|--------|---------|----------|\n| Replace all | `-c "content"` | Rewriting entire doc |\n| Append | `-a "content"` | Adding to end |\n| Section edit | `--section "2" -c "content"` | Updating one section |\n\n**Section edit is most efficient** - less context, safer.\n\n```bash\n# Update just section 3\nknowns doc edit "<path>" --section "3" -c "## 3. New Content\n\nUpdated section content..."\n```\n\n## Document Structure\n\nUse numbered headings for `--section` to work:\n\n```markdown\n# Title (H1 - only one)\n\n## 1. Overview\n...\n\n## 2. Installation\n...\n\n## 3. Configuration\n...\n```\n\n## Remember\n\n- Search before creating (avoid duplicates)\n- Always use `--smart` when reading\n- Use `--section` for targeted edits\n- Use numbered headings\n- Reference docs with `@doc/<path>`\n';
43477
+
43478
+ // src/templates/skills/knowns.init/SKILL.md
43479
+ var SKILL_default3 = '---\nname: knowns.init\ndescription: Use at the start of a new session to read project docs, understand context, and see current state\n---\n\n# Session Initialization\n\nInitialize a session by reading project documentation and understanding current state.\n\n**Announce at start:** "I\'m using the knowns.init skill to initialize this session."\n\n**Core principle:** READ DOCS BEFORE DOING ANYTHING ELSE.\n\n## The Process\n\n### Step 1: List Available Documentation\n\n```bash\nknowns doc list --plain\n```\n\n### Step 2: Read Core Documents\n\n**Priority order:**\n\n```bash\n# 1. Project overview (always read)\nknowns doc "README" --plain --smart\n\n# 2. Architecture (if exists)\nknowns doc "ARCHITECTURE" --plain --smart\n\n# 3. Conventions (if exists)\nknowns doc "CONVENTIONS" --plain --smart\n```\n\n### Step 3: Check Current State\n\n```bash\n# Active timer?\nknowns time status\n\n# Tasks in progress\nknowns task list --status in-progress --plain\n\n# High priority todos\nknowns task list --status todo --plain | head -20\n```\n\n### Step 4: Summarize Context\n\nProvide a brief summary:\n\n```markdown\n## Session Context\n\n### Project\n- **Name**: [from config]\n- **Purpose**: [from README]\n\n### Key Docs Available\n- README: [brief note]\n- ARCHITECTURE: [if exists]\n- CONVENTIONS: [if exists]\n\n### Current State\n- Tasks in progress: [count]\n- Active timer: [yes/no]\n\n### Ready for\n- Working on tasks\n- Creating documentation\n- Answering questions about codebase\n```\n\n## Quick Commands After Init\n\n```bash\n# Work on a task\n/knowns.task <id>\n\n# Search for something\nknowns search "<query>" --plain\n\n# View a doc\nknowns doc "<path>" --plain --smart\n```\n\n## When to Re-Initialize\n\n**Run init again when:**\n- Starting a new session\n- Major project changes occurred\n- Switching to different area of project\n- Context feels stale\n\n## What to Learn from Docs\n\nFrom **README**:\n- Project purpose and scope\n- Key features\n- Getting started info\n\nFrom **ARCHITECTURE**:\n- System design\n- Component structure\n- Key decisions\n\nFrom **CONVENTIONS**:\n- Coding standards\n- Naming conventions\n- File organization\n\n## Remember\n\n- Always read docs first\n- Check for active work (in-progress tasks)\n- Summarize context for reference\n- Re-init when switching areas\n';
43480
+
43481
+ // src/templates/skills/knowns.research/SKILL.md
43482
+ var SKILL_default4 = '---\nname: knowns.research\ndescription: Use when you need to understand existing code, find patterns, or explore the codebase before implementation\n---\n\n# Researching the Codebase\n\nUnderstand existing patterns and implementation before making changes.\n\n**Announce at start:** "I\'m using the knowns.research skill to research [topic]."\n\n**Core principle:** UNDERSTAND WHAT EXISTS BEFORE ADDING NEW CODE.\n\n## The Process\n\n### Step 1: Search Documentation\n\n```bash\n# Search docs for topic\nknowns search "<topic>" --type doc --plain\n\n# Read relevant docs\nknowns doc "<path>" --plain --smart\n```\n\n### Step 2: Search Completed Tasks\n\n```bash\n# Find similar work that was done\nknowns search "<keywords>" --type task --status done --plain\n\n# View task for implementation details\nknowns task <id> --plain\n```\n\n**Learn from history** - completed tasks often contain valuable insights.\n\n### Step 3: Search Codebase\n\n```bash\n# Find files by name pattern\nfind . -name "*<pattern>*" -type f | grep -v node_modules | head -20\n\n# Search code content\ngrep -r "<pattern>" --include="*.ts" --include="*.tsx" -l | head -20\n```\n\n### Step 4: Analyze Patterns\n\nLook for:\n- How similar features are implemented\n- Common patterns used\n- File/folder structure conventions\n- Naming conventions\n- Error handling patterns\n\n### Step 5: Document Findings\n\n```markdown\n## Research: [Topic]\n\n### Existing Implementations\n- `src/path/file.ts`: Does X\n- `src/path/other.ts`: Handles Y\n\n### Patterns Found\n- Pattern 1: Used for...\n- Pattern 2: Applied when...\n\n### Related Docs\n- @doc/path1 - Covers X\n- @doc/path2 - Explains Y\n\n### Recommendations\nBased on research:\n1. Reuse X from Y\n2. Follow pattern Z\n3. Avoid approach W because...\n```\n\n## Research Checklist\n\n- [ ] Searched documentation\n- [ ] Reviewed similar completed tasks\n- [ ] Found existing code patterns\n- [ ] Identified reusable components\n- [ ] Noted conventions to follow\n\n## After Research\n\nUse findings in task:\n```bash\n# Create informed task\nknowns task create "<title>" \\\n -d "Based on research: use pattern from X" \\\n --ac "Follow pattern in src/..." \\\n --ac "Reuse component Y"\n\n# Or update existing task plan\nknowns task edit <id> --plan $\'1. Based on research...\n2. Reuse pattern from...\'\n```\n\n## What to Look For\n\n| Looking For | Where to Check |\n|-------------|----------------|\n| Conventions | @doc/CONVENTIONS, existing code |\n| Patterns | @doc/patterns/*, similar features |\n| Utilities | src/utils/*, src/lib/* |\n| Examples | Completed tasks, tests |\n| API design | Existing endpoints, @doc/api/* |\n\n## When to Research\n\n**Always research before:**\n- Implementing new features\n- Adding new patterns\n- Making architectural decisions\n\n**Skip research for:**\n- Simple bug fixes with clear cause\n- Trivial changes following obvious patterns\n\n## Remember\n\n- Check docs and tasks first\n- Look at how similar things are done\n- Note file locations for reference\n- Look at tests for expected behavior\n- Document findings for future reference\n';
43483
+
43484
+ // src/templates/skills/knowns.task.brainstorm/SKILL.md
43485
+ var SKILL_default5 = '---\nname: knowns.task.brainstorm\ndescription: Use when requirements are unclear, multiple approaches exist, or you need to explore solutions before planning\n---\n\n# Brainstorming for Tasks\n\nConvert vague requirements into concrete design through structured questioning and exploration.\n\n**Announce at start:** "I\'m using the knowns.task.brainstorm skill to explore approaches."\n\n**Core principle:** UNDERSTAND THE PROBLEM BEFORE PROPOSING SOLUTIONS.\n\n## The Process\n\n### Phase 1: Discovery\n\n**One question at a time.** Don\'t overwhelm with multiple questions.\n\nPrefer multiple-choice when possible:\n```\nWhich approach do you prefer?\nA) Quick solution with trade-offs\nB) Comprehensive solution, more effort\nC) Something else (describe)\n```\n\nQuestions to clarify:\n- What problem are we solving?\n- Who are the users/stakeholders?\n- What are the constraints?\n- What does success look like?\n\n### Phase 2: Research Existing Patterns\n\n```bash\n# Search docs for related patterns\nknowns search "<topic>" --type doc --plain\n\n# Check how similar things were done\nknowns search "<keywords>" --type task --status done --plain\n```\n\n**Learn from history** - completed tasks often contain implementation insights.\n\n### Phase 3: Explore Approaches\n\nPresent 2-3 options with trade-offs:\n\n```markdown\n## Option A: [Name]\n- **Approach**: Brief description\n- **Pros**: What\'s good\n- **Cons**: What\'s challenging\n- **Effort**: Low/Medium/High\n\n## Option B: [Name]\n- **Approach**: Brief description\n- **Pros**: What\'s good\n- **Cons**: What\'s challenging\n- **Effort**: Low/Medium/High\n```\n\n**Lead with your recommendation** and explain why.\n\n### Phase 4: Validate and Document\n\nAfter agreement:\n- Summarize the chosen approach\n- Identify potential risks\n- Define acceptance criteria\n\nIf creating a new task:\n```bash\nknowns task create "<title>" \\\n -d "Based on brainstorm: <key decisions>" \\\n --ac "Criterion 1" \\\n --ac "Criterion 2"\n```\n\nIf updating existing task:\n```bash\nknowns task edit $ARGUMENTS -d "Updated based on brainstorm..."\n```\n\n## When to Use This Skill\n\n**Good candidates:**\n- Vague requirements ("make it faster", "improve UX")\n- Multiple valid approaches exist\n- Significant effort involved\n- New territory for the project\n\n**Skip for:**\n- Clear, well-defined tasks\n- Bug fixes with obvious solutions\n- Simple additions following existing patterns\n\n## Red Flags\n\n**You\'re doing it wrong if:**\n- Proposing solutions before understanding the problem\n- Asking too many questions at once\n- Not researching existing patterns first\n- Skipping trade-off analysis\n\n## Remember\n\n- One question at a time\n- Research existing patterns first\n- Present options with trade-offs\n- Lead with your recommendation\n- Document the decision\n';
43486
+
43487
+ // src/templates/skills/knowns.task.extract/SKILL.md
43488
+ var SKILL_default6 = '---\nname: knowns.task.extract\ndescription: Use when extracting reusable patterns, solutions, or knowledge from completed tasks into documentation\n---\n\n# Extracting Knowledge from Tasks\n\nConvert task-specific implementations into reusable project documentation.\n\n**Announce at start:** "I\'m using the knowns.task.extract skill to extract knowledge from task [ID]."\n\n**Core principle:** ONLY EXTRACT GENERALIZABLE KNOWLEDGE.\n\n## The Process\n\n### Step 1: Review Completed Task\n\n```bash\nknowns task $ARGUMENTS --plain\n```\n\nLook for:\n- Implementation patterns used\n- Problems solved\n- Decisions made\n- Lessons learned\n\n### Step 2: Identify Extractable Knowledge\n\n**Good candidates for extraction:**\n- Reusable code patterns\n- Error handling approaches\n- Integration patterns\n- Performance solutions\n- Security practices\n- API design decisions\n\n**NOT good for extraction:**\n- Task-specific details\n- One-time fixes\n- Context-dependent solutions\n\n### Step 3: Search for Existing Docs\n\n```bash\n# Check if pattern already documented\nknowns search "<pattern/topic>" --type doc --plain\n\n# List related docs\nknowns doc list --tag pattern --plain\n```\n\n**Don\'t duplicate.** Update existing docs when possible.\n\n### Step 4: Create or Update Documentation\n\n**If new pattern - create doc:**\n\n```bash\nknowns doc create "Pattern: <Name>" \\\n -d "Reusable pattern for <purpose>" \\\n -t "pattern,<domain>" \\\n -f "patterns"\n```\n\n**Add content:**\n\n```bash\nknowns doc edit "patterns/<name>" -c "$(cat <<\'EOF\'\n# Pattern: <Name>\n\n## 1. Problem\nWhat problem this pattern solves.\n\n## 2. Solution\nHow to implement the pattern.\n\n## 3. Example\n```typescript\n// Code example from the task\n```\n\n## 4. When to Use\n- Situation 1\n- Situation 2\n\n## 5. Source\nDiscovered in @task-<id>\nEOF\n)"\n```\n\n**If updating existing doc:**\n\n```bash\nknowns doc edit "<path>" -a "\n\n## Additional: <Topic>\n\nFrom @task-<id>: <new insight or example>\n"\n```\n\n### Step 5: Link Back to Task\n\n```bash\nknowns task edit $ARGUMENTS --append-notes "\u{1F4DA} Extracted to @doc/patterns/<name>"\n```\n\n## What to Extract\n\n| From Task | Extract As |\n|-----------|------------|\n| New code pattern | Pattern doc |\n| Error solution | Troubleshooting guide |\n| API integration | Integration guide |\n| Performance fix | Performance patterns |\n| Security approach | Security guidelines |\n\n## Document Templates\n\n### Pattern Template\n```markdown\n# Pattern: <Name>\n\n## Problem\nWhat this solves.\n\n## Solution\nHow to implement.\n\n## Example\nWorking code.\n\n## When to Use\nWhen to apply this pattern.\n```\n\n### Guide Template\n```markdown\n# Guide: <Topic>\n\n## Overview\nWhat this covers.\n\n## Steps\n1. Step one\n2. Step two\n\n## Common Issues\n- Issue and solution\n```\n\n## Quality Checklist\n\n- [ ] Knowledge is generalizable (not task-specific)\n- [ ] Includes working example\n- [ ] Explains when to use\n- [ ] Links back to source task\n- [ ] Tagged appropriately\n\n## Remember\n\n- Only extract generalizable knowledge\n- Search before creating (avoid duplicates)\n- Include practical examples\n- Reference source task\n- Tag docs for discoverability\n';
43489
+
43490
+ // src/templates/skills/knowns.task.reopen/SKILL.md
43491
+ var SKILL_default7 = '---\nname: knowns.task.reopen\ndescription: Use when reopening a completed task to add new requirements, fix issues, or extend functionality\n---\n\n# Reopening Tasks\n\nReopen completed tasks properly with time tracking and requirement documentation.\n\n**Announce at start:** "I\'m using the knowns.task.reopen skill to reopen task [ID]."\n\n**Core principle:** DOCUMENT WHY THE TASK IS REOPENED.\n\n## The Process\n\n### Step 1: View Current Task State\n\n```bash\nknowns task $ARGUMENTS --plain\n```\n\nVerify:\n- Task is currently `done`\n- Understand what was implemented\n- Review implementation notes\n\n### Step 2: Reopen and Start Timer\n\n```bash\n# Set back to in-progress\nknowns task edit $ARGUMENTS -s in-progress\n\n# Start timer (REQUIRED)\nknowns time start $ARGUMENTS\n```\n\n### Step 3: Document Reopen Reason\n\n```bash\nknowns task edit $ARGUMENTS --append-notes "\u{1F504} Reopened: <reason>"\n```\n\n**Common reasons:**\n- User requested changes\n- Bug found in implementation\n- New requirements added\n- Missed acceptance criteria\n\n### Step 4: Add New Requirements\n\n```bash\n# Add new acceptance criteria\nknowns task edit $ARGUMENTS --ac "New requirement 1"\nknowns task edit $ARGUMENTS --ac "Fix: issue description"\n```\n\n### Step 5: Update Plan (if needed)\n\n```bash\nknowns task edit $ARGUMENTS --plan $\'Previous plan + new steps:\n1. Original step (done)\n2. Original step (done)\n3. NEW: Address new requirement\n4. NEW: Fix reported issue\'\n```\n\n**Present updated plan and WAIT for approval.**\n\n### Step 6: Implement and Complete\n\nFollow normal task completion flow:\n\n```bash\n# Check new ACs as completed\nknowns task edit $ARGUMENTS --check-ac <new-index>\nknowns task edit $ARGUMENTS --append-notes "\u2713 Done: new requirement"\n\n# Stop timer\nknowns time stop\n\n# Mark done again\nknowns task edit $ARGUMENTS -s done\n```\n\n## When to Reopen vs Create New Task\n\n| Reopen Existing | Create New Task |\n|-----------------|-----------------|\n| Small fix/change | Major new feature |\n| Related to original work | Unrelated work |\n| Same context needed | Different context |\n| Quick addition | Significant scope |\n\n**Rule of thumb:** If it takes < 30 mins and relates to original task, reopen. Otherwise, create new task with reference.\n\n## Creating Follow-up Task Instead\n\n```bash\nknowns task create "Follow-up: <description>" \\\n -d "Related to @task-$ARGUMENTS" \\\n --ac "New requirement"\n```\n\n## Remember\n\n- Always document reopen reason\n- Start timer when reopening\n- Add new AC for traceability\n- Stop timer when done\n- Consider if new task is more appropriate\n';
43492
+
43493
+ // src/templates/skills/knowns.task/SKILL.md
43494
+ var SKILL_default8 = '---\nname: knowns.task\ndescription: Use when working on a Knowns task - take ownership, research, plan, implement, complete with proper tracking\n---\n\n# Working on a Knowns Task\n\nExecute the complete task workflow with proper documentation reading, planning, and time tracking.\n\n**Announce at start:** "I\'m using the knowns.task skill to work on task [ID]."\n\n**Core principle:** NO IMPLEMENTATION WITHOUT RESEARCH AND APPROVED PLAN FIRST.\n\n## The Process\n\n### Phase 1: Take Ownership\n\n```bash\n# View task details\nknowns task $ARGUMENTS --plain\n\n# Take task and start timer\nknowns task edit $ARGUMENTS -s in-progress -a @me\nknowns time start $ARGUMENTS\n```\n\n**Timer is mandatory.** Time tracking data informs project estimation and identifies bottlenecks.\n\n### Phase 2: Research (MANDATORY)\n\n**Follow ALL refs in task output:**\n- `@task-<id>` \u2192 `knowns task <id> --plain`\n- `@doc/<path>` \u2192 `knowns doc "<path>" --plain --smart`\n\n```bash\n# Search related docs\nknowns search "<keywords>" --type doc --plain\n\n# Check similar completed tasks (learn from history)\nknowns search "<keywords>" --type task --status done --plain\n```\n\n**Why research matters:**\n- Prevents reinventing existing patterns\n- Ensures consistency with project conventions\n- Reveals reusable code/utilities\n- Identifies potential blockers early\n\n### Phase 3: Plan (WAIT FOR APPROVAL)\n\n```bash\nknowns task edit $ARGUMENTS --plan $\'1. Step one (see @doc/relevant-doc)\n2. Step two\n3. Add tests\n4. Update documentation\'\n```\n\n**Present plan to user and WAIT.** Do not proceed until explicit approval.\n\nIf using brainstorm first:\n- **RELATED SKILL:** Use knowns.task.brainstorm for complex requirements\n\n### Phase 4: Implement\n\nFor each piece of work completed:\n\n```bash\n# Check AC only AFTER work is done\nknowns task edit $ARGUMENTS --check-ac 1\nknowns task edit $ARGUMENTS --append-notes "\u2713 Done: brief description"\n```\n\n**Red flags - you\'re doing it wrong if:**\n- Checking AC before work is actually complete\n- Making changes not in the approved plan\n- Skipping tests\n\n**If scope changes during implementation:**\n1. Stop and ask user\n2. Add new AC: `knowns task edit $ARGUMENTS --ac "New requirement"`\n3. Update plan if needed\n\n### Phase 5: Complete\n\n```bash\n# Add implementation summary\nknowns task edit $ARGUMENTS --notes $\'## Summary\nWhat was done and key decisions.\n\n## Changes\n- Change 1\n- Change 2\'\n\n# Stop timer (REQUIRED!)\nknowns time stop\n\n# Mark done\nknowns task edit $ARGUMENTS -s done\n```\n\n## When to Stop and Ask\n\n**STOP immediately when:**\n- Requirements are unclear or contradictory\n- You hit a blocker not addressed in the plan\n- The approach isn\'t working after 2-3 attempts\n- You need to make changes outside approved scope\n\n**Ask for clarification rather than guessing.**\n\n## Common Mistakes\n\n| Wrong | Right |\n|-------|-------|\n| Check AC before work done | Check AC only AFTER completing |\n| Skip research phase | Always read related docs first |\n| Start coding before plan approval | Wait for explicit approval |\n| Forget to stop timer | Always `knowns time stop` |\n| Use `-a` for acceptance criteria | Use `--ac` (not `-a`) |\n\n## Remember\n\n- Research before planning\n- Plan before implementing\n- Check AC after completing (not before)\n- Timer is mandatory\n- Ask when blocked, don\'t guess\n';
43495
+
43496
+ // src/templates/skills/index.ts
43497
+ function parseSkillFrontmatter(content) {
43498
+ const lines = content.trim().split("\n");
43499
+ let name = "";
43500
+ let description = "";
43501
+ if (lines[0] === "---") {
43502
+ for (let i = 1; i < lines.length; i++) {
43503
+ if (lines[i] === "---") break;
43504
+ const nameMatch = lines[i].match(/^name:\s*(.+)$/);
43505
+ if (nameMatch) name = nameMatch[1].trim();
43506
+ const descMatch = lines[i].match(/^description:\s*(.+)$/);
43507
+ if (descMatch) description = descMatch[1].trim();
43508
+ }
43509
+ }
43510
+ return { name, description };
43511
+ }
43512
+ function createSkill(content, folderName) {
43513
+ const { name, description } = parseSkillFrontmatter(content);
43514
+ return {
43515
+ name: name || folderName,
43516
+ folderName,
43517
+ description,
43518
+ content: content.trim()
43519
+ };
43520
+ }
43521
+ var SKILL_TASK = createSkill(SKILL_default8, "knowns.task");
43522
+ var SKILL_TASK_BRAINSTORM = createSkill(SKILL_default5, "knowns.task.brainstorm");
43523
+ var SKILL_TASK_REOPEN = createSkill(SKILL_default7, "knowns.task.reopen");
43524
+ var SKILL_TASK_EXTRACT = createSkill(SKILL_default6, "knowns.task.extract");
43525
+ var SKILL_DOC = createSkill(SKILL_default2, "knowns.doc");
43526
+ var SKILL_COMMIT = createSkill(SKILL_default, "knowns.commit");
43527
+ var SKILL_INIT = createSkill(SKILL_default3, "knowns.init");
43528
+ var SKILL_RESEARCH = createSkill(SKILL_default4, "knowns.research");
43529
+ var SKILLS = [
43530
+ // Task skills
43531
+ SKILL_TASK,
43532
+ SKILL_TASK_BRAINSTORM,
43533
+ SKILL_TASK_REOPEN,
43534
+ SKILL_TASK_EXTRACT,
43535
+ // Doc skills
43536
+ SKILL_DOC,
43537
+ // Git skills
43538
+ SKILL_COMMIT,
43539
+ // Session skills
43540
+ SKILL_INIT,
43541
+ SKILL_RESEARCH
43542
+ ];
43543
+
43472
43544
  // src/commands/agents.ts
43473
43545
  import { existsSync } from "node:fs";
43474
43546
  import { mkdir as mkdir3, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
@@ -43476,16 +43548,16 @@ import { dirname, join as join3 } from "node:path";
43476
43548
  var import_prompts = __toESM(require_prompts3(), 1);
43477
43549
 
43478
43550
  // src/templates/guidelines/cli/commands-reference.md
43479
- var commands_reference_default = '# Commands Reference\n\n## task create\n\n```bash\nknowns task create <title> [options]\n```\n\n| Flag | Short | Purpose |\n| --------------- | ----- | --------------------------------- |\n| `--description` | `-d` | Task description |\n| `--ac` | | Acceptance criterion (repeatable) |\n| `--labels` | `-l` | Comma-separated labels |\n| `--assignee` | `-a` | Assign to user \u26A0\uFE0F |\n| `--priority` | | low/medium/high |\n| `--status` | `-s` | Initial status |\n| `--parent` | | Parent task ID (raw ID only!) |\n\n**\u26A0\uFE0F `-a` = assignee, NOT acceptance criteria! Use `--ac` for AC.**\n\n---\n\n## task edit\n\n```bash\nknowns task edit <id> [options]\n```\n\n| Flag | Short | Purpose |\n| ---------------- | ----- | ------------------------ |\n| `--title` | `-t` | Change title |\n| `--description` | `-d` | Change description |\n| `--status` | `-s` | Change status |\n| `--priority` | | Change priority |\n| `--labels` | `-l` | Set labels |\n| `--assignee` | `-a` | Assign user \u26A0\uFE0F |\n| `--parent` | | Move to parent |\n| `--ac` | | Add acceptance criterion |\n| `--check-ac` | | Mark AC done (1-indexed) |\n| `--uncheck-ac` | | Unmark AC (1-indexed) |\n| `--remove-ac` | | Delete AC (1-indexed) |\n| `--plan` | | Set implementation plan |\n| `--notes` | | Replace notes |\n| `--append-notes` | | Add to notes |\n\n**\u26A0\uFE0F `-a` = assignee, NOT acceptance criteria! Use `--ac` for AC.**\n\n---\n\n## task view/list\n\n```bash\nknowns task <id> --plain # View single task\nknowns task list --plain # List all\nknowns task list --status in-progress --plain\nknowns task list --assignee @me --plain\nknowns task list --tree --plain # Tree hierarchy\n```\n\n---\n\n## doc create\n\n```bash\nknowns doc create <title> [options]\n```\n\n| Flag | Short | Purpose |\n| --------------- | ----- | -------------------- |\n| `--description` | `-d` | Description |\n| `--tags` | `-t` | Comma-separated tags |\n| `--folder` | `-f` | Folder path |\n\n### Document Structure Best Practice\n\nWhen creating/editing docs, use clear heading structure for `--toc` and `--section` to work properly:\n\n```markdown\n# Main Title (H1 - only one)\n\n## 1. Overview\n\nBrief introduction...\n\n## 2. Installation\n\nStep-by-step guide...\n\n## 3. Configuration\n\n### 3.1 Basic Config\n\n...\n\n### 3.2 Advanced Config\n\n...\n\n## 4. API Reference\n\n...\n```\n\n**Writing rules:**\n\n- Use numbered headings (`## 1. Overview`) for easy `--section "1"` access\n- Keep H1 for title only, use H2 for main sections\n- Use H3 for subsections within H2\n- Each section should be self-contained (readable without context)\n\n**Reading workflow:**\n\n```bash\n# Step 1: Check size first\nknowns doc <path> --info --plain\n# \u2192 If <2000 tokens: read directly with --plain\n# \u2192 If >2000 tokens: continue to step 2\n\n# Step 2: Get table of contents\nknowns doc <path> --toc --plain\n\n# Step 3: Read specific section\nknowns doc <path> --section "2" --plain\n```\n\n---\n\n## doc edit\n\n```bash\nknowns doc edit <name> [options]\n```\n\n| Flag | Short | Purpose |\n| ---------------- | ----- | ----------------------------------------- |\n| `--title` | `-t` | Change title |\n| `--description` | `-d` | Change description |\n| `--tags` | | Set tags |\n| `--content` | `-c` | Replace content (or section if --section) |\n| `--append` | `-a` | Append content \u26A0\uFE0F |\n| `--section` | | Target section to replace (use with -c) |\n| `--content-file` | | Content from file |\n| `--append-file` | | Append from file |\n\n**\u26A0\uFE0F In doc edit, `-a` = append content, NOT assignee!**\n\n### Section Edit (Context-Efficient)\n\nReplace only a specific section instead of entire document:\n\n```bash\n# Step 1: View TOC to find section\nknowns doc readme --toc --plain\n\n# Step 2: Edit only that section\nknowns doc edit readme --section "2. Installation" -c "New content here..."\nknowns doc edit readme --section "2" -c "New content..." # By number works too\n```\n\nThis reduces context usage significantly - no need to read/write entire document.\n\n---\n\n## doc view/list\n\n```bash\nknowns doc <path> --plain # View single doc\nknowns doc list --plain # List all\nknowns doc list --tag api --plain # Filter by tag\n```\n\n### Large Documents (--info, --toc, --section)\n\nFor large documents, check size first with `--info`, then use `--toc` and `--section`:\n\n```bash\n# Step 1: Check document size and token count\nknowns doc readme --info --plain\n# Output: Size: 42,461 chars (~12,132 tokens) | Headings: 83\n# Recommendation: Document is large. Use --toc first, then --section.\n\n# Step 2: View table of contents\nknowns doc readme --toc --plain\n\n# Step 3: Read specific section by title or number\nknowns doc readme --section "5. Sync" --plain\nknowns doc readme --section "3" --plain\n```\n\n**Decision flow:**\n\n- `--info` \u2192 Check size (~tokens) \u2192 If >2000 tokens, use --toc/--section\n- `--toc` \u2192 Get heading list \u2192 Choose section to read\n- `--section` \u2192 Read only what you need\n\n---\n\n## time\n\n```bash\nknowns time start <id> # REQUIRED when taking task\nknowns time stop # REQUIRED when completing\nknowns time pause\nknowns time resume\nknowns time status\nknowns time add <id> <duration> -n "Note" -d "2025-01-01"\n```\n\n---\n\n## search\n\n```bash\nknowns search "query" --plain\nknowns search "auth" --type task --plain\nknowns search "api" --type doc --plain\nknowns search "bug" --type task --status in-progress --priority high --plain\n```\n\n---\n\n## Multi-line Input (Bash/Zsh)\n\n```bash\nknowns task edit <id> --plan $\'1. Step\\n2. Step\\n3. Step\'\n```\n';
43551
+ var commands_reference_default = '# Commands Reference\n\n## task create\n\n```bash\nknowns task create <title> [options]\n```\n\n| Flag | Short | Purpose |\n| --------------- | ----- | --------------------------------- |\n| `--description` | `-d` | Task description |\n| `--ac` | | Acceptance criterion (repeatable) |\n| `--labels` | `-l` | Comma-separated labels |\n| `--assignee` | `-a` | Assign to user \u26A0\uFE0F |\n| `--priority` | | low/medium/high |\n| `--status` | `-s` | Initial status |\n| `--parent` | | Parent task ID (raw ID only!) |\n\n**\u26A0\uFE0F `-a` = assignee, NOT acceptance criteria! Use `--ac` for AC.**\n\n---\n\n## task edit\n\n```bash\nknowns task edit <id> [options]\n```\n\n| Flag | Short | Purpose |\n| ---------------- | ----- | ------------------------ |\n| `--title` | `-t` | Change title |\n| `--description` | `-d` | Change description |\n| `--status` | `-s` | Change status |\n| `--priority` | | Change priority |\n| `--labels` | `-l` | Set labels |\n| `--assignee` | `-a` | Assign user \u26A0\uFE0F |\n| `--parent` | | Move to parent |\n| `--ac` | | Add acceptance criterion |\n| `--check-ac` | | Mark AC done (1-indexed) |\n| `--uncheck-ac` | | Unmark AC (1-indexed) |\n| `--remove-ac` | | Delete AC (1-indexed) |\n| `--plan` | | Set implementation plan |\n| `--notes` | | Replace notes |\n| `--append-notes` | | Add to notes |\n\n**\u26A0\uFE0F `-a` = assignee, NOT acceptance criteria! Use `--ac` for AC.**\n\n---\n\n## task view/list\n\n```bash\nknowns task <id> --plain # View single task\nknowns task list --plain # List all\nknowns task list --status in-progress --plain\nknowns task list --assignee @me --plain\nknowns task list --tree --plain # Tree hierarchy\n```\n\n---\n\n## doc create\n\n```bash\nknowns doc create <title> [options]\n```\n\n| Flag | Short | Purpose |\n| --------------- | ----- | -------------------- |\n| `--description` | `-d` | Description |\n| `--tags` | `-t` | Comma-separated tags |\n| `--folder` | `-f` | Folder path |\n\n### Document Structure Best Practice\n\nWhen creating/editing docs, use clear heading structure for `--toc` and `--section` to work properly:\n\n```markdown\n# Main Title (H1 - only one)\n\n## 1. Overview\n\nBrief introduction...\n\n## 2. Installation\n\nStep-by-step guide...\n\n## 3. Configuration\n\n### 3.1 Basic Config\n\n...\n\n### 3.2 Advanced Config\n\n...\n\n## 4. API Reference\n\n...\n```\n\n**Writing rules:**\n\n- Use numbered headings (`## 1. Overview`) for easy `--section "1"` access\n- Keep H1 for title only, use H2 for main sections\n- Use H3 for subsections within H2\n- Each section should be self-contained (readable without context)\n\n**Reading workflow:**\n\n```bash\n# Always use --smart (handles both small and large docs automatically)\nknowns doc <path> --plain --smart\n\n# If doc is large, --smart returns TOC, then read specific section:\nknowns doc <path> --plain --section "2"\n```\n\n---\n\n## doc edit\n\n```bash\nknowns doc edit <name> [options]\n```\n\n| Flag | Short | Purpose |\n| ---------------- | ----- | ----------------------------------------- |\n| `--title` | `-t` | Change title |\n| `--description` | `-d` | Change description |\n| `--tags` | | Set tags |\n| `--content` | `-c` | Replace content (or section if --section) |\n| `--append` | `-a` | Append content \u26A0\uFE0F |\n| `--section` | | Target section to replace (use with -c) |\n| `--content-file` | | Content from file |\n| `--append-file` | | Append from file |\n\n**\u26A0\uFE0F In doc edit, `-a` = append content, NOT assignee!**\n\n### Section Edit (Context-Efficient)\n\nReplace only a specific section instead of entire document:\n\n```bash\n# Step 1: View TOC to find section\nknowns doc readme --toc --plain\n\n# Step 2: Edit only that section\nknowns doc edit readme --section "2. Installation" -c "New content here..."\nknowns doc edit readme --section "2" -c "New content..." # By number works too\n```\n\nThis reduces context usage significantly - no need to read/write entire document.\n\n---\n\n## doc view/list\n\n```bash\nknowns doc <path> --plain # View single doc\nknowns doc list --plain # List all\nknowns doc list --tag api --plain # Filter by tag\n```\n\n### Reading Documents (--smart)\n\n**ALWAYS use `--smart` when reading documents.** It automatically handles both small and large docs:\n\n```bash\n# Always use --smart (recommended)\nknowns doc <path> --plain --smart\n```\n\n**Behavior:**\n\n- **Small doc (\u22642000 tokens)**: Returns full content automatically\n- **Large doc (>2000 tokens)**: Returns stats + TOC, then use `--section` to read specific parts\n\n```bash\n# Example with large doc:\nknowns doc readme --plain --smart\n# Output: Size: ~12,132 tokens | TOC with numbered sections\n# Hint: Use --section <number> to read specific section\n\n# Then read specific section:\nknowns doc readme --plain --section 3\n```\n\n### Manual Control (--info, --toc, --section)\n\nIf you need manual control instead of `--smart`:\n\n```bash\nknowns doc <path> --info --plain # Check size/tokens\nknowns doc <path> --toc --plain # View table of contents\nknowns doc <path> --section "3" --plain # Read specific section\n```\n\n---\n\n## time\n\n```bash\nknowns time start <id> # REQUIRED when taking task\nknowns time stop # REQUIRED when completing\nknowns time pause\nknowns time resume\nknowns time status\nknowns time add <id> <duration> -n "Note" -d "2025-01-01"\n```\n\n---\n\n## search\n\n```bash\nknowns search "query" --plain\nknowns search "auth" --type task --plain\nknowns search "api" --type doc --plain\nknowns search "bug" --type task --status in-progress --priority high --plain\n```\n\n---\n\n## Multi-line Input (Bash/Zsh)\n\n```bash\nknowns task edit <id> --plan $\'1. Step\\n2. Step\\n3. Step\'\n```\n';
43480
43552
 
43481
43553
  // src/templates/guidelines/cli/common-mistakes.md
43482
- var common_mistakes_default = '# Common Mistakes\n\n## \u26A0\uFE0F CRITICAL: The -a Flag\n\n| Command | `-a` Means | NOT This! |\n|---------|------------|-----------|\n| `task create/edit` | `--assignee` | ~~acceptance criteria~~ |\n| `doc edit` | `--append` | ~~assignee~~ |\n\n```bash\n# \u274C WRONG (sets assignee to garbage!)\nknowns task edit 35 -a "Criterion text"\n\n# \u2705 CORRECT (use --ac)\nknowns task edit 35 --ac "Criterion text"\n```\n\n---\n\n## Quick Reference\n\n| \u274C DON\'T | \u2705 DO |\n|----------|-------|\n| Edit .md files directly | Use CLI commands |\n| `-a "criterion"` | `--ac "criterion"` |\n| `--parent task-48` | `--parent 48` (raw ID) |\n| `--plain` with create/edit | `--plain` only for view/list |\n| Check AC before work done | Check AC AFTER work done |\n| Code before plan approval | Wait for user approval |\n| Code before reading docs | Read docs FIRST |\n| Skip time tracking | Always `time start`/`stop` |\n| Ignore task refs | Follow ALL `@.knowns/...` refs |\n\n---\n\n## Error Recovery\n\n| Problem | Solution |\n|---------|----------|\n| Set assignee to AC text | `knowns task edit <id> -a @me` |\n| Forgot to stop timer | `knowns time add <id> <duration>` |\n| Checked AC too early | `knowns task edit <id> --uncheck-ac N` |\n| Task not found | `knowns task list --plain` |\n';
43554
+ var common_mistakes_default = '# Common Mistakes\n\n## \u26A0\uFE0F CRITICAL: The -a Flag\n\n| Command | `-a` Means | NOT This! |\n|---------|------------|-----------|\n| `task create/edit` | `--assignee` | ~~acceptance criteria~~ |\n| `doc edit` | `--append` | ~~assignee~~ |\n\n```bash\n# \u274C WRONG (sets assignee to garbage!)\nknowns task edit 35 -a "Criterion text"\n\n# \u2705 CORRECT (use --ac)\nknowns task edit 35 --ac "Criterion text"\n```\n\n---\n\n## Quick Reference\n\n| \u274C DON\'T | \u2705 DO |\n|----------|-------|\n| Edit .md files directly | Use CLI commands |\n| `-a "criterion"` | `--ac "criterion"` |\n| `--parent task-48` | `--parent 48` (raw ID) |\n| `--plain` with create/edit | `--plain` only for view/list |\n| Check AC before work done | Check AC AFTER work done |\n| Code before plan approval | Wait for user approval |\n| Code before reading docs | Read docs FIRST |\n| Skip time tracking | Always `time start`/`stop` |\n| Ignore task refs | Follow ALL `@task-xxx` and `@doc/xxx` refs |\n\n---\n\n## Error Recovery\n\n| Problem | Solution |\n|---------|----------|\n| Set assignee to AC text | `knowns task edit <id> -a @me` |\n| Forgot to stop timer | `knowns time add <id> <duration>` |\n| Checked AC too early | `knowns task edit <id> --uncheck-ac N` |\n| Task not found | `knowns task list --plain` |\n';
43483
43555
 
43484
43556
  // src/templates/guidelines/cli/context-optimization.md
43485
- var context_optimization_default = '# Context Optimization\n\nOptimize your context usage to work more efficiently within token limits.\n\n---\n\n## Output Format\n\n```bash\n# \u274C Verbose output\nknowns task 42 --json\n\n# \u2705 Compact output (always use --plain)\nknowns task 42 --plain\n```\n\n---\n\n## Search Before Read\n\n```bash\n# \u274C Reading all docs to find info\nknowns doc "doc1" --plain\nknowns doc "doc2" --plain\nknowns doc "doc3" --plain\n\n# \u2705 Search first, then read only relevant docs\nknowns search "authentication" --type doc --plain\nknowns doc "security-patterns" --plain # Only the relevant one\n```\n\n---\n\n## Selective File Reading\n\n```bash\n# \u274C Reading entire large file\nRead file (2000+ lines)\n\n# \u2705 Read specific sections\nRead file with offset=100 limit=50\n```\n\n---\n\n## Large Documents (--info, --toc, --section)\n\nFor large documents, check size first with `--info`:\n\n```bash\n# \u274C Reading entire large document (may be truncated)\nknowns doc readme --plain\n\n# \u2705 Step 1: Check document size first\nknowns doc readme --info --plain\n# Output: Size: 42,461 chars (~12,132 tokens) | Headings: 83\n\n# \u2705 Step 2: View table of contents (if >2000 tokens)\nknowns doc readme --toc --plain\n\n# \u2705 Step 3: Read only the section you need\nknowns doc readme --section "3. Config" --plain\n```\n\n**Decision flow:** `--info` \u2192 check tokens \u2192 if >2000, use `--toc` then `--section`\n\n---\n\n## Compact Notes\n\n```bash\n# \u274C Verbose notes\nknowns task edit 42 --append-notes "I have successfully completed the implementation of the authentication middleware which validates JWT tokens and handles refresh logic..."\n\n# \u2705 Compact notes\nknowns task edit 42 --append-notes "\u2713 Auth middleware + JWT validation done"\n```\n\n---\n\n## Avoid Redundant Operations\n\n| Don\'t | Do Instead |\n| -------------------------------- | --------------------------- |\n| Re-read files already in context | Reference from memory |\n| List tasks/docs multiple times | List once, remember results |\n| Quote entire file contents | Summarize key points |\n| Repeat full error messages | Reference error briefly |\n\n---\n\n## Efficient Workflow\n\n| Phase | Context-Efficient Approach |\n| -------------- | ------------------------------ |\n| **Research** | Search \u2192 Read only matches |\n| **Planning** | Brief plan, not detailed prose |\n| **Coding** | Read only files being modified |\n| **Notes** | Bullet points, not paragraphs |\n| **Completion** | Summary, not full log |\n\n---\n\n## Quick Rules\n\n1. **Always `--plain`** - Never use `--json` unless specifically needed\n2. **Search first** - Don\'t read all docs hoping to find info\n3. **Read selectively** - Use offset/limit for large files\n4. **Use --info first** - Check doc size before reading, then --toc/--section if needed\n5. **Write concise** - Compact notes, not essays\n6. **Don\'t repeat** - Reference context already loaded\n7. **Summarize** - Key points, not full quotes\n';
43557
+ var context_optimization_default = '# Context Optimization\n\nOptimize your context usage to work more efficiently within token limits.\n\n---\n\n## Output Format\n\n```bash\n# \u274C Verbose output\nknowns task 42 --json\n\n# \u2705 Compact output (always use --plain)\nknowns task 42 --plain\n```\n\n---\n\n## Search Before Read\n\n```bash\n# \u274C Reading all docs to find info\nknowns doc "doc1" --plain\nknowns doc "doc2" --plain\nknowns doc "doc3" --plain\n\n# \u2705 Search first, then read only relevant docs\nknowns search "authentication" --type doc --plain\nknowns doc "security-patterns" --plain # Only the relevant one\n```\n\n---\n\n## Selective File Reading\n\n```bash\n# \u274C Reading entire large file\nRead file (2000+ lines)\n\n# \u2705 Read specific sections\nRead file with offset=100 limit=50\n```\n\n---\n\n## Reading Documents (--smart)\n\n**ALWAYS use `--smart` when reading documents.** It automatically handles both small and large docs:\n\n```bash\n# \u274C Reading without --smart (may get truncated large doc)\nknowns doc readme --plain\n\n# \u2705 Always use --smart\nknowns doc readme --plain --smart\n# Small doc \u2192 returns full content\n# Large doc \u2192 returns stats + TOC\n\n# \u2705 If doc is large, read specific section:\nknowns doc readme --plain --section 3\n```\n\n**`--smart` behavior:**\n\n- **\u22642000 tokens**: Returns full content automatically\n- **>2000 tokens**: Returns stats + TOC, then use `--section <number>`\n\n---\n\n## Compact Notes\n\n```bash\n# \u274C Verbose notes\nknowns task edit 42 --append-notes "I have successfully completed the implementation of the authentication middleware which validates JWT tokens and handles refresh logic..."\n\n# \u2705 Compact notes\nknowns task edit 42 --append-notes "\u2713 Auth middleware + JWT validation done"\n```\n\n---\n\n## Avoid Redundant Operations\n\n| Don\'t | Do Instead |\n| -------------------------------- | --------------------------- |\n| Re-read files already in context | Reference from memory |\n| List tasks/docs multiple times | List once, remember results |\n| Quote entire file contents | Summarize key points |\n| Repeat full error messages | Reference error briefly |\n\n---\n\n## Efficient Workflow\n\n| Phase | Context-Efficient Approach |\n| -------------- | ------------------------------ |\n| **Research** | Search \u2192 Read only matches |\n| **Planning** | Brief plan, not detailed prose |\n| **Coding** | Read only files being modified |\n| **Notes** | Bullet points, not paragraphs |\n| **Completion** | Summary, not full log |\n\n---\n\n## Quick Rules\n\n1. **Always `--plain`** - Never use `--json` unless specifically needed\n2. **Always `--smart`** - Use `--smart` when reading docs (auto-handles size)\n3. **Search first** - Don\'t read all docs hoping to find info\n4. **Read selectively** - Use offset/limit for large files\n5. **Write concise** - Compact notes, not essays\n6. **Don\'t repeat** - Reference context already loaded\n7. **Summarize** - Key points, not full quotes\n';
43486
43558
 
43487
43559
  // src/templates/guidelines/cli/core-rules.md
43488
- var core_rules_default = '# Core Rules\n\nYou MUST follow these rules. If you cannot follow any rule, stop and ask for guidance before proceeding.\n\n---\n\n## \u{1F3AF} The Golden Rule\n\n**If you want to change ANYTHING in a task or doc, use CLI commands or MCP tools. NEVER edit .md files directly.**\n\nWhy? Direct file editing breaks metadata synchronization, Git tracking, and relationships.\n\n---\n\n## \u26A0\uFE0F CRITICAL: The -a Flag Confusion\n\nThe `-a` flag means DIFFERENT things in different commands:\n\n| Command | `-a` Means | NOT This! |\n|---------|------------|-----------|\n| `task create` | `--assignee` (assign user) | ~~acceptance criteria~~ |\n| `task edit` | `--assignee` (assign user) | ~~acceptance criteria~~ |\n| `doc edit` | `--append` (append content) | ~~assignee~~ |\n\n### Acceptance Criteria: Use --ac\n\n```bash\n# \u274C WRONG: -a is assignee, NOT acceptance criteria!\nknowns task edit 35 -a "- [ ] Criterion" # Sets assignee to garbage!\nknowns task create "Title" -a "Criterion" # Sets assignee to garbage!\n\n# \u2705 CORRECT: Use --ac for acceptance criteria\nknowns task edit 35 --ac "Criterion one"\nknowns task edit 35 --ac "Criterion two"\nknowns task create "Title" --ac "Criterion one" --ac "Criterion two"\n```\n\n---\n\n## Core Principles\n\n| Rule | Description |\n|------|-------------|\n| **CLI/MCP Only** | Use commands for ALL operations. NEVER edit .md files directly |\n| **Docs First** | Read project docs BEFORE planning or coding |\n| **Time Tracking** | Always start timer when taking task, stop when done |\n| **Plan Approval** | Share plan with user, WAIT for approval before coding |\n| **Check AC After Work** | Only mark acceptance criteria done AFTER completing the work |\n\n---\n\n## The --plain Flag\n\n**ONLY for view/list/search commands (NOT create/edit):**\n\n```bash\n# \u2705 CORRECT\nknowns task <id> --plain\nknowns task list --plain\nknowns doc "path" --plain\nknowns doc list --plain\nknowns search "query" --plain\n\n# \u274C WRONG (create/edit don\'t support --plain)\nknowns task create "Title" --plain # ERROR!\nknowns task edit <id> -s done --plain # ERROR!\nknowns doc create "Title" --plain # ERROR!\nknowns doc edit "name" -c "..." --plain # ERROR!\n```\n\n---\n\n## Reference System\n\n| Context | Task Format | Doc Format |\n|---------|-------------|------------|\n| **Writing** (input) | `@task-<id>` | `@doc/<path>` |\n| **Reading** (output) | `@.knowns/tasks/task-<id>` | `@.knowns/docs/<path>.md` |\n\nFollow refs recursively until complete context gathered.\n\n---\n\n## Task IDs\n\n| Format | Example | Notes |\n|--------|---------|-------|\n| Sequential | `48`, `49` | Legacy numeric |\n| Hierarchical | `48.1`, `48.2` | Legacy subtasks |\n| Random | `qkh5ne` | Current (6-char) |\n\n**CRITICAL:** Use raw ID for `--parent`:\n```bash\n# \u2705 CORRECT\nknowns task create "Title" --parent 48\n\n# \u274C WRONG\nknowns task create "Title" --parent task-48\n```\n\n---\n\n## Status & Priority\n\n| Status | When |\n|--------|------|\n| `todo` | Not started (default) |\n| `in-progress` | Currently working |\n| `in-review` | PR submitted |\n| `blocked` | Waiting on dependency |\n| `done` | All criteria met |\n\n| Priority | Level |\n|----------|-------|\n| `low` | Nice-to-have |\n| `medium` | Normal (default) |\n| `high` | Urgent |\n';
43560
+ var core_rules_default = '# Core Rules\n\nYou MUST follow these rules. If you cannot follow any rule, stop and ask for guidance before proceeding.\n\n---\n\n## \u{1F3AF} The Golden Rule\n\n**If you want to change ANYTHING in a task or doc, use CLI commands or MCP tools. NEVER edit .md files directly.**\n\nWhy? Direct file editing breaks metadata synchronization, Git tracking, and relationships.\n\n---\n\n## \u26A0\uFE0F CRITICAL: The -a Flag Confusion\n\nThe `-a` flag means DIFFERENT things in different commands:\n\n| Command | `-a` Means | NOT This! |\n|---------|------------|-----------|\n| `task create` | `--assignee` (assign user) | ~~acceptance criteria~~ |\n| `task edit` | `--assignee` (assign user) | ~~acceptance criteria~~ |\n| `doc edit` | `--append` (append content) | ~~assignee~~ |\n\n### Acceptance Criteria: Use --ac\n\n```bash\n# \u274C WRONG: -a is assignee, NOT acceptance criteria!\nknowns task edit 35 -a "- [ ] Criterion" # Sets assignee to garbage!\nknowns task create "Title" -a "Criterion" # Sets assignee to garbage!\n\n# \u2705 CORRECT: Use --ac for acceptance criteria\nknowns task edit 35 --ac "Criterion one"\nknowns task edit 35 --ac "Criterion two"\nknowns task create "Title" --ac "Criterion one" --ac "Criterion two"\n```\n\n---\n\n## Core Principles\n\n| Rule | Description |\n|------|-------------|\n| **CLI/MCP Only** | Use commands for ALL operations. NEVER edit .md files directly |\n| **Docs First** | Read project docs BEFORE planning or coding |\n| **Time Tracking** | Always start timer when taking task, stop when done |\n| **Plan Approval** | Share plan with user, WAIT for approval before coding |\n| **Check AC After Work** | Only mark acceptance criteria done AFTER completing the work |\n\n---\n\n## The --plain Flag\n\n**ONLY for view/list/search commands (NOT create/edit):**\n\n```bash\n# \u2705 CORRECT\nknowns task <id> --plain\nknowns task list --plain\nknowns doc "path" --plain\nknowns doc list --plain\nknowns search "query" --plain\n\n# \u274C WRONG (create/edit don\'t support --plain)\nknowns task create "Title" --plain # ERROR!\nknowns task edit <id> -s done --plain # ERROR!\nknowns doc create "Title" --plain # ERROR!\nknowns doc edit "name" -c "..." --plain # ERROR!\n```\n\n---\n\n## Reference System\n\n| Type | Format | Example |\n|------|--------|---------|\n| **Task ref** | `@task-<id>` | `@task-pdyd2e` |\n| **Doc ref** | `@doc/<path>` | `@doc/patterns/auth` |\n\nFollow refs recursively until complete context gathered.\n\n---\n\n## Task IDs\n\n| Format | Example | Notes |\n|--------|---------|-------|\n| Sequential | `48`, `49` | Legacy numeric |\n| Hierarchical | `48.1`, `48.2` | Legacy subtasks |\n| Random | `qkh5ne` | Current (6-char) |\n\n**CRITICAL:** Use raw ID for `--parent`:\n```bash\n# \u2705 CORRECT\nknowns task create "Title" --parent 48\n\n# \u274C WRONG\nknowns task create "Title" --parent task-48\n```\n\n---\n\n## Status & Priority\n\n| Status | When |\n|--------|------|\n| `todo` | Not started (default) |\n| `in-progress` | Currently working |\n| `in-review` | PR submitted |\n| `blocked` | Waiting on dependency |\n| `done` | All criteria met |\n\n| Priority | Level |\n|----------|-------|\n| `low` | Nice-to-have |\n| `medium` | Normal (default) |\n| `high` | Urgent |\n';
43489
43561
 
43490
43562
  // src/templates/guidelines/cli/workflow-completion.md
43491
43563
  var workflow_completion_default = '# Task Completion\n\n## Definition of Done\n\nA task is **Done** when ALL of these are complete:\n\n| Requirement | Command |\n|-------------|---------|\n| All AC checked | `knowns task edit <id> --check-ac N` |\n| Notes added | `knowns task edit <id> --notes "Summary"` |\n| Timer stopped | `knowns time stop` |\n| Status = done | `knowns task edit <id> -s done` |\n| Tests pass | Run test suite |\n\n---\n\n## Completion Steps\n\n```bash\n# 1. Verify all AC are checked\nknowns task <id> --plain\n\n# 2. Add implementation notes\nknowns task edit <id> --notes $\'## Summary\nWhat was done and key decisions.\'\n\n# 3. Stop timer (REQUIRED!)\nknowns time stop\n\n# 4. Mark done\nknowns task edit <id> -s done\n```\n\n---\n\n## Post-Completion Changes\n\nIf user requests changes after task is done:\n\n```bash\nknowns task edit <id> -s in-progress # Reopen\nknowns time start <id> # Restart timer\nknowns task edit <id> --ac "Fix: description"\nknowns task edit <id> --append-notes "\u{1F504} Reopened: reason"\n# Complete work, then follow completion steps again\n```\n\n---\n\n## Checklist\n\n- [ ] All AC checked (`--check-ac`)\n- [ ] Notes added (`--notes`)\n- [ ] Timer stopped (`time stop`)\n- [ ] Tests pass\n- [ ] Status = done (`-s done`)\n';
@@ -43494,7 +43566,7 @@ var workflow_completion_default = '# Task Completion\n\n## Definition of Done\n\
43494
43566
  var workflow_creation_default = '# Task Creation\n\n## Before Creating\n\n```bash\n# Search for existing tasks first\nknowns search "keyword" --type task --plain\n```\n\n---\n\n## Create Task\n\n```bash\nknowns task create "Clear title (WHAT)" \\\n -d "Description (WHY)" \\\n --ac "Outcome 1" \\\n --ac "Outcome 2" \\\n --priority medium \\\n -l "labels"\n```\n\n---\n\n## Quality Guidelines\n\n### Title\n| \u274C Bad | \u2705 Good |\n|--------|---------|\n| Do auth stuff | Add JWT authentication |\n| Fix bug | Fix login timeout |\n\n### Description\nExplain WHY. Include doc refs: `@doc/security-patterns`\n\n### Acceptance Criteria\n**Outcome-focused, NOT implementation steps:**\n\n| \u274C Bad | \u2705 Good |\n|--------|---------|\n| Add handleLogin() function | User can login |\n| Use bcrypt | Passwords are hashed |\n| Add try-catch | Errors return proper HTTP codes |\n\n---\n\n## Subtasks\n\n```bash\nknowns task create "Parent task"\nknowns task create "Subtask" --parent 48 # Raw ID only!\n```\n\n---\n\n## Anti-Patterns\n\n- \u274C Too many AC in one task \u2192 Split into multiple tasks\n- \u274C Implementation steps as AC \u2192 Write outcomes instead\n- \u274C Skip search \u2192 Always check existing tasks first\n';
43495
43567
 
43496
43568
  // src/templates/guidelines/cli/workflow-execution.md
43497
- var workflow_execution_default = '# Task Execution\n\n## Step 1: Take Task\n\n```bash\nknowns task edit <id> -s in-progress -a @me\nknowns time start <id> # REQUIRED!\n```\n\n---\n\n## Step 2: Research\n\n```bash\n# Read task and follow ALL refs\nknowns task <id> --plain\n# @.knowns/docs/xxx.md \u2192 knowns doc "xxx" --plain\n# @.knowns/tasks/task-YY \u2192 knowns task YY --plain\n\n# Search related docs\nknowns search "keyword" --type doc --plain\n\n# Check similar done tasks\nknowns search "keyword" --type task --status done --plain\n```\n\n---\n\n## Step 3: Plan (BEFORE coding!)\n\n```bash\nknowns task edit <id> --plan $\'1. Research (see @doc/xxx)\n2. Implement\n3. Test\n4. Document\'\n```\n\n**\u26A0\uFE0F Share plan with user. WAIT for approval before coding.**\n\n---\n\n## Step 4: Implement\n\n```bash\n# Check AC only AFTER work is done\nknowns task edit <id> --check-ac 1\nknowns task edit <id> --append-notes "\u2713 Done: feature X"\n```\n\n---\n\n## Scope Changes\n\nIf new requirements emerge during work:\n\n```bash\n# Small: Add to current task\nknowns task edit <id> --ac "New requirement"\nknowns task edit <id> --append-notes "\u26A0\uFE0F Scope updated: reason"\n\n# Large: Ask user first, then create follow-up\nknowns task create "Follow-up: feature" -d "From task <id>"\n```\n\n**\u26A0\uFE0F Don\'t silently expand scope. Ask user first.**\n\n---\n\n## Key Rules\n\n1. **Plan before code** - Capture approach first\n2. **Wait for approval** - Don\'t start without OK\n3. **Check AC after work** - Not before\n4. **Ask on scope changes** - Don\'t expand silently\n';
43569
+ var workflow_execution_default = '# Task Execution\n\n## Step 1: Take Task\n\n```bash\nknowns task edit <id> -s in-progress -a @me\nknowns time start <id> # REQUIRED!\n```\n\n---\n\n## Step 2: Research\n\n```bash\n# Read task and follow ALL refs\nknowns task <id> --plain\n# @doc/xxx \u2192 knowns doc "xxx" --plain\n# @task-YY \u2192 knowns task YY --plain\n\n# Search related docs\nknowns search "keyword" --type doc --plain\n\n# Check similar done tasks\nknowns search "keyword" --type task --status done --plain\n```\n\n---\n\n## Step 3: Plan (BEFORE coding!)\n\n```bash\nknowns task edit <id> --plan $\'1. Research (see @doc/xxx)\n2. Implement\n3. Test\n4. Document\'\n```\n\n**\u26A0\uFE0F Share plan with user. WAIT for approval before coding.**\n\n---\n\n## Step 4: Implement\n\n```bash\n# Check AC only AFTER work is done\nknowns task edit <id> --check-ac 1\nknowns task edit <id> --append-notes "\u2713 Done: feature X"\n```\n\n---\n\n## Scope Changes\n\nIf new requirements emerge during work:\n\n```bash\n# Small: Add to current task\nknowns task edit <id> --ac "New requirement"\nknowns task edit <id> --append-notes "\u26A0\uFE0F Scope updated: reason"\n\n# Large: Ask user first, then create follow-up\nknowns task create "Follow-up: feature" -d "From task <id>"\n```\n\n**\u26A0\uFE0F Don\'t silently expand scope. Ask user first.**\n\n---\n\n## Key Rules\n\n1. **Plan before code** - Capture approach first\n2. **Wait for approval** - Don\'t start without OK\n3. **Check AC after work** - Not before\n4. **Ask on scope changes** - Don\'t expand silently\n';
43498
43570
 
43499
43571
  // src/templates/guidelines/cli/index.ts
43500
43572
  var CLI_CORE_RULES = core_rules_default.trim();
@@ -43574,16 +43646,16 @@ ${content}
43574
43646
  };
43575
43647
 
43576
43648
  // src/templates/guidelines/mcp/commands-reference.md
43577
- var commands_reference_default2 = '# MCP Tools Reference\n\n## mcp**knowns**create_task\n\nCreate a new task.\n\n```json\n{\n "title": "Task title",\n "description": "Task description",\n "status": "todo",\n "priority": "medium",\n "labels": ["label1", "label2"],\n "assignee": "@me",\n "parent": "parent-task-id"\n}\n```\n\n| Parameter | Required | Description |\n| ------------- | -------- | --------------------------------------- |\n| `title` | Yes | Task title |\n| `description` | No | Task description |\n| `status` | No | todo/in-progress/in-review/blocked/done |\n| `priority` | No | low/medium/high |\n| `labels` | No | Array of labels |\n| `assignee` | No | Assignee (use @me for self) |\n| `parent` | No | Parent task ID for subtasks |\n\n**Note:** Acceptance criteria must be added via `mcp__knowns__update_task` after creation.\n\n---\n\n## mcp**knowns**update_task\n\nUpdate task fields.\n\n```json\n{\n "taskId": "abc123",\n "title": "New title",\n "description": "New description",\n "status": "in-progress",\n "priority": "high",\n "labels": ["updated"],\n "assignee": "@me"\n}\n```\n\n| Parameter | Required | Description |\n| ------------- | -------- | ----------------- |\n| `taskId` | Yes | Task ID to update |\n| `title` | No | New title |\n| `description` | No | New description |\n| `status` | No | New status |\n| `priority` | No | New priority |\n| `labels` | No | New labels array |\n| `assignee` | No | New assignee |\n\n**Note:** For acceptance criteria, implementation plan, and notes - use CLI commands or edit task file directly through knowns CLI.\n\n---\n\n## mcp**knowns**get_task\n\nGet a task by ID.\n\n```json\n{\n "taskId": "abc123"\n}\n```\n\n---\n\n## mcp**knowns**list_tasks\n\nList tasks with optional filters.\n\n```json\n{\n "status": "in-progress",\n "priority": "high",\n "assignee": "@me",\n "label": "bug"\n}\n```\n\nAll parameters are optional filters.\n\n---\n\n## mcp**knowns**search_tasks\n\nSearch tasks by query string.\n\n```json\n{\n "query": "authentication"\n}\n```\n\n---\n\n## mcp**knowns**get_doc\n\nGet a documentation file by path.\n\n```json\n{\n "path": "README"\n}\n```\n\nPath can be filename or folder/filename (without .md extension).\n\n### Large Documents (info, toc, section)\n\nFor large documents, check size first with `info`, then use `toc` and `section`:\n\n```json\n// Step 1: Check document size and token count\n{\n "path": "readme",\n "info": true\n}\n// Response: { stats: { chars: 42461, estimatedTokens: 12132, headingCount: 83 }, recommendation: "..." }\n\n// Step 2: Get table of contents\n{\n "path": "readme",\n "toc": true\n}\n\n// Step 3: Read specific section by title or number\n{\n "path": "readme",\n "section": "5. Sync"\n}\n```\n\n| Parameter | Description |\n| --------- | -------------------------------------------------------- |\n| `info` | Set `true` to get stats (size, tokens, headings) only |\n| `toc` | Set `true` to get table of contents only |\n| `section` | Section title or number to read (e.g., "5. Sync" or "3") |\n\n**Decision flow:**\n\n- `info: true` \u2192 Check estimatedTokens \u2192 If >2000, use toc/section\n- `toc: true` \u2192 Get heading list \u2192 Choose section to read\n- `section: "X"` \u2192 Read only what you need\n\n---\n\n## mcp**knowns**list_docs\n\nList all documentation files.\n\n```json\n{\n "tag": "api"\n}\n```\n\nOptional `tag` parameter to filter by tag.\n\n---\n\n## mcp**knowns**create_doc\n\nCreate a new documentation file.\n\n```json\n{\n "title": "Doc Title",\n "description": "Doc description",\n "tags": ["tag1", "tag2"],\n "folder": "guides",\n "content": "Initial content"\n}\n```\n\n### Document Structure Best Practice\n\nWhen creating/updating docs, use clear heading structure for `toc` and `section` to work properly:\n\n```markdown\n# Main Title (H1 - only one)\n\n## 1. Overview\n\nBrief introduction...\n\n## 2. Installation\n\nStep-by-step guide...\n\n## 3. Configuration\n\n### 3.1 Basic Config\n\n...\n\n### 3.2 Advanced Config\n\n...\n\n## 4. API Reference\n\n...\n```\n\n**Writing rules:**\n\n- Use numbered headings (`## 1. Overview`) for easy `section: "1"` access\n- Keep H1 for title only, use H2 for main sections\n- Use H3 for subsections within H2\n- Each section should be self-contained (readable without context)\n\n**Reading workflow:**\n\n```json\n// Step 1: Check size first\n{ "path": "<path>", "info": true }\n// \u2192 If estimatedTokens <2000: read directly (no options)\n// \u2192 If estimatedTokens >2000: continue to step 2\n\n// Step 2: Get table of contents\n{ "path": "<path>", "toc": true }\n\n// Step 3: Read specific section\n{ "path": "<path>", "section": "2" }\n```\n\n---\n\n## mcp**knowns**update_doc\n\nUpdate an existing documentation file.\n\n```json\n{\n "path": "README",\n "title": "New Title",\n "description": "New description",\n "tags": ["new", "tags"],\n "content": "Replace content",\n "appendContent": "Append to existing"\n}\n```\n\nUse either `content` (replace) or `appendContent` (append), not both.\n\n### Section Edit (Context-Efficient)\n\nReplace only a specific section instead of entire document:\n\n```json\n// Step 1: View TOC to find section\n{ "path": "readme", "toc": true }\n\n// Step 2: Edit only that section\n{\n "path": "readme",\n "section": "2. Installation",\n "content": "New content here..."\n}\n```\n\nThis reduces context usage significantly - no need to read/write entire document.\n\n---\n\n## mcp**knowns**search_docs\n\nSearch documentation by query.\n\n```json\n{\n "query": "authentication",\n "tag": "api"\n}\n```\n\n---\n\n## mcp**knowns**start_time\n\nStart time tracking for a task.\n\n```json\n{\n "taskId": "abc123"\n}\n```\n\n---\n\n## mcp**knowns**stop_time\n\nStop time tracking.\n\n```json\n{\n "taskId": "abc123"\n}\n```\n\n---\n\n## mcp**knowns**add_time\n\nManually add a time entry.\n\n```json\n{\n "taskId": "abc123",\n "duration": "2h30m",\n "note": "Optional note",\n "date": "2025-01-15"\n}\n```\n\n---\n\n## mcp**knowns**get_time_report\n\nGet time tracking report.\n\n```json\n{\n "from": "2025-01-01",\n "to": "2025-01-31",\n "groupBy": "task"\n}\n```\n\n`groupBy` can be: task, label, or status.\n\n---\n\n## mcp**knowns**get_board\n\nGet current board state with tasks grouped by status.\n\n```json\n{}\n```\n\nNo parameters required.\n';
43649
+ var commands_reference_default2 = '# MCP Tools Reference\n\n## mcp**knowns**create_task\n\nCreate a new task.\n\n```json\n{\n "title": "Task title",\n "description": "Task description",\n "status": "todo",\n "priority": "medium",\n "labels": ["label1", "label2"],\n "assignee": "@me",\n "parent": "parent-task-id"\n}\n```\n\n| Parameter | Required | Description |\n| ------------- | -------- | --------------------------------------- |\n| `title` | Yes | Task title |\n| `description` | No | Task description |\n| `status` | No | todo/in-progress/in-review/blocked/done |\n| `priority` | No | low/medium/high |\n| `labels` | No | Array of labels |\n| `assignee` | No | Assignee (use @me for self) |\n| `parent` | No | Parent task ID for subtasks |\n\n**Note:** Acceptance criteria must be added via `mcp__knowns__update_task` after creation.\n\n---\n\n## mcp**knowns**update_task\n\nUpdate task fields.\n\n```json\n{\n "taskId": "abc123",\n "title": "New title",\n "description": "New description",\n "status": "in-progress",\n "priority": "high",\n "labels": ["updated"],\n "assignee": "@me"\n}\n```\n\n| Parameter | Required | Description |\n| ------------- | -------- | ----------------- |\n| `taskId` | Yes | Task ID to update |\n| `title` | No | New title |\n| `description` | No | New description |\n| `status` | No | New status |\n| `priority` | No | New priority |\n| `labels` | No | New labels array |\n| `assignee` | No | New assignee |\n\n**Note:** For acceptance criteria, implementation plan, and notes - use CLI commands or edit task file directly through knowns CLI.\n\n---\n\n## mcp**knowns**get_task\n\nGet a task by ID.\n\n```json\n{\n "taskId": "abc123"\n}\n```\n\n---\n\n## mcp**knowns**list_tasks\n\nList tasks with optional filters.\n\n```json\n{\n "status": "in-progress",\n "priority": "high",\n "assignee": "@me",\n "label": "bug"\n}\n```\n\nAll parameters are optional filters.\n\n---\n\n## mcp**knowns**search_tasks\n\nSearch tasks by query string.\n\n```json\n{\n "query": "authentication"\n}\n```\n\n---\n\n## mcp**knowns**get_doc\n\nGet a documentation file by path.\n\n```json\n{\n "path": "README"\n}\n```\n\nPath can be filename or folder/filename (without .md extension).\n\n### Reading Documents (smart)\n\n**ALWAYS use `smart: true` when reading documents.** It automatically handles both small and large docs:\n\n```json\n// Always use smart (recommended)\n{\n "path": "readme",\n "smart": true\n}\n```\n\n**Behavior:**\n\n- **Small doc (\u22642000 tokens)**: Returns full content automatically\n- **Large doc (>2000 tokens)**: Returns stats + TOC with numbered sections\n\n```json\n// If doc is large, smart returns TOC, then read specific section:\n{\n "path": "readme",\n "section": "3"\n}\n```\n\n| Parameter | Description |\n| --------- | -------------------------------------------------------------- |\n| `smart` | **Recommended.** Auto-return full content or TOC based on size |\n| `section` | Read specific section by number (e.g., "3") or title |\n\n### Manual Control (info, toc, section)\n\nIf you need manual control instead of `smart`:\n\n```json\n{ "path": "readme", "info": true } // Check size/tokens\n{ "path": "readme", "toc": true } // View table of contents\n{ "path": "readme", "section": "3" } // Read specific section\n```\n\n---\n\n## mcp**knowns**list_docs\n\nList all documentation files.\n\n```json\n{\n "tag": "api"\n}\n```\n\nOptional `tag` parameter to filter by tag.\n\n---\n\n## mcp**knowns**create_doc\n\nCreate a new documentation file.\n\n```json\n{\n "title": "Doc Title",\n "description": "Doc description",\n "tags": ["tag1", "tag2"],\n "folder": "guides",\n "content": "Initial content"\n}\n```\n\n### Document Structure Best Practice\n\nWhen creating/updating docs, use clear heading structure for `toc` and `section` to work properly:\n\n```markdown\n# Main Title (H1 - only one)\n\n## 1. Overview\n\nBrief introduction...\n\n## 2. Installation\n\nStep-by-step guide...\n\n## 3. Configuration\n\n### 3.1 Basic Config\n\n...\n\n### 3.2 Advanced Config\n\n...\n\n## 4. API Reference\n\n...\n```\n\n**Writing rules:**\n\n- Use numbered headings (`## 1. Overview`) for easy `section: "1"` access\n- Keep H1 for title only, use H2 for main sections\n- Use H3 for subsections within H2\n- Each section should be self-contained (readable without context)\n\n**Reading workflow:**\n\n```json\n// Always use smart (handles both small and large docs automatically)\n{ "path": "<path>", "smart": true }\n\n// If doc is large, smart returns TOC, then read specific section:\n{ "path": "<path>", "section": "2" }\n```\n\n---\n\n## mcp**knowns**update_doc\n\nUpdate an existing documentation file.\n\n```json\n{\n "path": "README",\n "title": "New Title",\n "description": "New description",\n "tags": ["new", "tags"],\n "content": "Replace content",\n "appendContent": "Append to existing"\n}\n```\n\nUse either `content` (replace) or `appendContent` (append), not both.\n\n### Section Edit (Context-Efficient)\n\nReplace only a specific section instead of entire document:\n\n```json\n// Step 1: View TOC to find section\n{ "path": "readme", "toc": true }\n\n// Step 2: Edit only that section\n{\n "path": "readme",\n "section": "2. Installation",\n "content": "New content here..."\n}\n```\n\nThis reduces context usage significantly - no need to read/write entire document.\n\n---\n\n## mcp**knowns**search_docs\n\nSearch documentation by query.\n\n```json\n{\n "query": "authentication",\n "tag": "api"\n}\n```\n\n---\n\n## mcp**knowns**start_time\n\nStart time tracking for a task.\n\n```json\n{\n "taskId": "abc123"\n}\n```\n\n---\n\n## mcp**knowns**stop_time\n\nStop time tracking.\n\n```json\n{\n "taskId": "abc123"\n}\n```\n\n---\n\n## mcp**knowns**add_time\n\nManually add a time entry.\n\n```json\n{\n "taskId": "abc123",\n "duration": "2h30m",\n "note": "Optional note",\n "date": "2025-01-15"\n}\n```\n\n---\n\n## mcp**knowns**get_time_report\n\nGet time tracking report.\n\n```json\n{\n "from": "2025-01-01",\n "to": "2025-01-31",\n "groupBy": "task"\n}\n```\n\n`groupBy` can be: task, label, or status.\n\n---\n\n## mcp**knowns**get_board\n\nGet current board state with tasks grouped by status.\n\n```json\n{}\n```\n\nNo parameters required.\n';
43578
43650
 
43579
43651
  // src/templates/guidelines/mcp/common-mistakes.md
43580
- var common_mistakes_default2 = "# Common Mistakes (MCP)\n\n## Quick Reference\n\n| DON'T | DO |\n|-------|-----|\n| Edit .md files directly | Use MCP tools |\n| Skip time tracking | Always `start_time`/`stop_time` |\n| Check AC before work done | Check AC AFTER work done |\n| Code before plan approval | Wait for user approval |\n| Code before reading docs | Read docs FIRST |\n| Ignore task refs | Follow ALL `@.knowns/...` refs |\n| Use wrong task ID format | Use raw ID string |\n\n---\n\n## MCP vs CLI Usage\n\nSome operations require CLI (not available in MCP):\n\n| Operation | Tool |\n|-----------|------|\n| Add acceptance criteria | CLI: `--ac` |\n| Check/uncheck AC | CLI: `--check-ac`, `--uncheck-ac` |\n| Set implementation plan | CLI: `--plan` |\n| Add/append notes | CLI: `--notes`, `--append-notes` |\n| Create/update task basic fields | MCP tools |\n| Time tracking | MCP tools |\n| Read tasks/docs | MCP tools |\n| Search | MCP tools |\n\n---\n\n## Error Recovery\n\n| Problem | Solution |\n|---------|----------|\n| Forgot to stop timer | `mcp__knowns__add_time` with duration |\n| Wrong status | `mcp__knowns__update_task` to fix |\n| Task not found | `mcp__knowns__list_tasks` to find ID |\n| Need to uncheck AC | CLI: `knowns task edit <id> --uncheck-ac N` |\n";
43652
+ var common_mistakes_default2 = "# Common Mistakes (MCP)\n\n## Quick Reference\n\n| DON'T | DO |\n|-------|-----|\n| Edit .md files directly | Use MCP tools |\n| Skip time tracking | Always `start_time`/`stop_time` |\n| Check AC before work done | Check AC AFTER work done |\n| Code before plan approval | Wait for user approval |\n| Code before reading docs | Read docs FIRST |\n| Ignore task refs | Follow ALL `@task-xxx` and `@doc/xxx` refs |\n| Use wrong task ID format | Use raw ID string |\n\n---\n\n## MCP vs CLI Usage\n\nSome operations require CLI (not available in MCP):\n\n| Operation | Tool |\n|-----------|------|\n| Add acceptance criteria | CLI: `--ac` |\n| Check/uncheck AC | CLI: `--check-ac`, `--uncheck-ac` |\n| Set implementation plan | CLI: `--plan` |\n| Add/append notes | CLI: `--notes`, `--append-notes` |\n| Create/update task basic fields | MCP tools |\n| Time tracking | MCP tools |\n| Read tasks/docs | MCP tools |\n| Search | MCP tools |\n\n---\n\n## Error Recovery\n\n| Problem | Solution |\n|---------|----------|\n| Forgot to stop timer | `mcp__knowns__add_time` with duration |\n| Wrong status | `mcp__knowns__update_task` to fix |\n| Task not found | `mcp__knowns__list_tasks` to find ID |\n| Need to uncheck AC | CLI: `knowns task edit <id> --uncheck-ac N` |\n";
43581
43653
 
43582
43654
  // src/templates/guidelines/mcp/context-optimization.md
43583
- var context_optimization_default2 = '# Context Optimization (MCP)\n\nOptimize your context usage to work more efficiently within token limits.\n\n---\n\n## Search Before Read\n\n```json\n// DON\'T: Read all docs hoping to find info\nmcp__knowns__get_doc({ "path": "doc1" })\nmcp__knowns__get_doc({ "path": "doc2" })\nmcp__knowns__get_doc({ "path": "doc3" })\n\n// DO: Search first, then read only relevant docs\nmcp__knowns__search_docs({ "query": "authentication" })\nmcp__knowns__get_doc({ "path": "security-patterns" }) // Only the relevant one\n```\n\n---\n\n## Use Filters\n\n```json\n// DON\'T: List all tasks then filter manually\nmcp__knowns__list_tasks({})\n\n// DO: Use filters in the query\nmcp__knowns__list_tasks({\n "status": "in-progress",\n "assignee": "@me"\n})\n```\n\n---\n\n## Large Documents (info, toc, section)\n\nFor large documents, check size first with `info`:\n\n```json\n// DON\'T: Read entire large document (may be truncated)\nmcp__knowns__get_doc({ "path": "readme" })\n\n// DO: Step 1 - Check document size first\nmcp__knowns__get_doc({ "path": "readme", "info": true })\n// Response: { stats: { estimatedTokens: 12132 }, recommendation: "..." }\n\n// DO: Step 2 - Get table of contents (if >2000 tokens)\nmcp__knowns__get_doc({ "path": "readme", "toc": true })\n\n// DO: Step 3 - Read only the section you need\nmcp__knowns__get_doc({ "path": "readme", "section": "3. Config" })\n```\n\n**Decision flow:** `info: true` \u2192 check tokens \u2192 if >2000, use `toc` then `section`\n\n---\n\n## Compact Notes\n\n```bash\n# DON\'T: Verbose notes\nknowns task edit 42 --append-notes "I have successfully completed the implementation..."\n\n# DO: Compact notes\nknowns task edit 42 --append-notes "Done: Auth middleware + JWT validation"\n```\n\n---\n\n## Avoid Redundant Operations\n\n| Don\'t | Do Instead |\n| ------------------------------------- | --------------------------- |\n| Re-read tasks/docs already in context | Reference from memory |\n| List tasks/docs multiple times | List once, remember results |\n| Fetch same task repeatedly | Cache the result |\n\n---\n\n## Efficient Workflow\n\n| Phase | Context-Efficient Approach |\n| -------------- | ------------------------------ |\n| **Research** | Search -> Read only matches |\n| **Planning** | Brief plan, not detailed prose |\n| **Coding** | Read only files being modified |\n| **Notes** | Bullet points, not paragraphs |\n| **Completion** | Summary, not full log |\n\n---\n\n## Quick Rules\n\n1. **Search first** - Don\'t read all docs hoping to find info\n2. **Use filters** - Don\'t list everything then filter manually\n3. **Read selectively** - Only fetch what you need\n4. **Use info first** - Check doc size before reading, then toc/section if needed\n5. **Write concise** - Compact notes, not essays\n6. **Don\'t repeat** - Reference context already loaded\n7. **Summarize** - Key points, not full quotes\n';
43655
+ var context_optimization_default2 = '# Context Optimization (MCP)\n\nOptimize your context usage to work more efficiently within token limits.\n\n---\n\n## Search Before Read\n\n```json\n// DON\'T: Read all docs hoping to find info\nmcp__knowns__get_doc({ "path": "doc1" })\nmcp__knowns__get_doc({ "path": "doc2" })\nmcp__knowns__get_doc({ "path": "doc3" })\n\n// DO: Search first, then read only relevant docs\nmcp__knowns__search_docs({ "query": "authentication" })\nmcp__knowns__get_doc({ "path": "security-patterns" }) // Only the relevant one\n```\n\n---\n\n## Use Filters\n\n```json\n// DON\'T: List all tasks then filter manually\nmcp__knowns__list_tasks({})\n\n// DO: Use filters in the query\nmcp__knowns__list_tasks({\n "status": "in-progress",\n "assignee": "@me"\n})\n```\n\n---\n\n## Reading Documents (smart)\n\n**ALWAYS use `smart: true` when reading documents.** It automatically handles both small and large docs:\n\n```json\n// DON\'T: Read without smart (may get truncated large doc)\nmcp__knowns__get_doc({ "path": "readme" })\n\n// DO: Always use smart\nmcp__knowns__get_doc({ "path": "readme", "smart": true })\n// Small doc \u2192 returns full content\n// Large doc \u2192 returns stats + TOC\n\n// DO: If doc is large, read specific section\nmcp__knowns__get_doc({ "path": "readme", "section": "3" })\n```\n\n**`smart: true` behavior:**\n\n- **\u22642000 tokens**: Returns full content automatically\n- **>2000 tokens**: Returns stats + TOC, then use `section` parameter\n\n---\n\n## Compact Notes\n\n```bash\n# DON\'T: Verbose notes\nknowns task edit 42 --append-notes "I have successfully completed the implementation..."\n\n# DO: Compact notes\nknowns task edit 42 --append-notes "Done: Auth middleware + JWT validation"\n```\n\n---\n\n## Avoid Redundant Operations\n\n| Don\'t | Do Instead |\n| ------------------------------------- | --------------------------- |\n| Re-read tasks/docs already in context | Reference from memory |\n| List tasks/docs multiple times | List once, remember results |\n| Fetch same task repeatedly | Cache the result |\n\n---\n\n## Efficient Workflow\n\n| Phase | Context-Efficient Approach |\n| -------------- | ------------------------------ |\n| **Research** | Search -> Read only matches |\n| **Planning** | Brief plan, not detailed prose |\n| **Coding** | Read only files being modified |\n| **Notes** | Bullet points, not paragraphs |\n| **Completion** | Summary, not full log |\n\n---\n\n## Quick Rules\n\n1. **Always `smart: true`** - Use smart when reading docs (auto-handles size)\n2. **Search first** - Don\'t read all docs hoping to find info\n3. **Use filters** - Don\'t list everything then filter manually\n4. **Read selectively** - Only fetch what you need\n5. **Write concise** - Compact notes, not essays\n6. **Don\'t repeat** - Reference context already loaded\n7. **Summarize** - Key points, not full quotes\n';
43584
43656
 
43585
43657
  // src/templates/guidelines/mcp/core-rules.md
43586
- var core_rules_default2 = "# Core Rules (MCP)\n\nYou MUST follow these rules. If you cannot follow any rule, stop and ask for guidance before proceeding.\n\n---\n\n## The Golden Rule\n\n**If you want to change ANYTHING in a task or doc, use MCP tools. NEVER edit .md files directly.**\n\nWhy? Direct file editing breaks metadata synchronization, Git tracking, and relationships.\n\n---\n\n## Core Principles\n\n| Rule | Description |\n|------|-------------|\n| **MCP Tools Only** | Use MCP tools for ALL operations. NEVER edit .md files directly |\n| **Docs First** | Read project docs BEFORE planning or coding |\n| **Time Tracking** | Always start timer when taking task, stop when done |\n| **Plan Approval** | Share plan with user, WAIT for approval before coding |\n| **Check AC After Work** | Only mark acceptance criteria done AFTER completing the work |\n\n---\n\n## Reference System\n\n| Context | Task Format | Doc Format |\n|---------|-------------|------------|\n| **Writing** (input) | `@task-<id>` | `@doc/<path>` |\n| **Reading** (output) | `@.knowns/tasks/task-<id>` | `@.knowns/docs/<path>.md` |\n\nFollow refs recursively until complete context gathered.\n\n---\n\n## Task IDs\n\n| Format | Example | Notes |\n|--------|---------|-------|\n| Sequential | `48`, `49` | Legacy numeric |\n| Hierarchical | `48.1`, `48.2` | Legacy subtasks |\n| Random | `qkh5ne` | Current (6-char) |\n\n**CRITICAL:** Use raw ID (string) for all MCP tool calls.\n\n---\n\n## Status & Priority\n\n| Status | When |\n|--------|------|\n| `todo` | Not started (default) |\n| `in-progress` | Currently working |\n| `in-review` | PR submitted |\n| `blocked` | Waiting on dependency |\n| `done` | All criteria met |\n\n| Priority | Level |\n|----------|-------|\n| `low` | Nice-to-have |\n| `medium` | Normal (default) |\n| `high` | Urgent |\n";
43658
+ var core_rules_default2 = "# Core Rules (MCP)\n\nYou MUST follow these rules. If you cannot follow any rule, stop and ask for guidance before proceeding.\n\n---\n\n## The Golden Rule\n\n**If you want to change ANYTHING in a task or doc, use MCP tools. NEVER edit .md files directly.**\n\nWhy? Direct file editing breaks metadata synchronization, Git tracking, and relationships.\n\n---\n\n## Core Principles\n\n| Rule | Description |\n|------|-------------|\n| **MCP Tools Only** | Use MCP tools for ALL operations. NEVER edit .md files directly |\n| **Docs First** | Read project docs BEFORE planning or coding |\n| **Time Tracking** | Always start timer when taking task, stop when done |\n| **Plan Approval** | Share plan with user, WAIT for approval before coding |\n| **Check AC After Work** | Only mark acceptance criteria done AFTER completing the work |\n\n---\n\n## Reference System\n\n| Type | Format | Example |\n|------|--------|---------|\n| **Task ref** | `@task-<id>` | `@task-pdyd2e` |\n| **Doc ref** | `@doc/<path>` | `@doc/patterns/auth` |\n\nFollow refs recursively until complete context gathered.\n\n---\n\n## Task IDs\n\n| Format | Example | Notes |\n|--------|---------|-------|\n| Sequential | `48`, `49` | Legacy numeric |\n| Hierarchical | `48.1`, `48.2` | Legacy subtasks |\n| Random | `qkh5ne` | Current (6-char) |\n\n**CRITICAL:** Use raw ID (string) for all MCP tool calls.\n\n---\n\n## Status & Priority\n\n| Status | When |\n|--------|------|\n| `todo` | Not started (default) |\n| `in-progress` | Currently working |\n| `in-review` | PR submitted |\n| `blocked` | Waiting on dependency |\n| `done` | All criteria met |\n\n| Priority | Level |\n|----------|-------|\n| `low` | Nice-to-have |\n| `medium` | Normal (default) |\n| `high` | Urgent |\n";
43587
43659
 
43588
43660
  // src/templates/guidelines/mcp/workflow-completion.md
43589
43661
  var workflow_completion_default2 = '# Task Completion (MCP)\n\n## Definition of Done\n\nA task is **Done** when ALL of these are complete:\n\n| Requirement | How |\n|-------------|-----|\n| All AC checked | CLI: `knowns task edit <id> --check-ac N` |\n| Notes added | CLI: `knowns task edit <id> --notes "Summary"` |\n| Timer stopped | MCP: `mcp__knowns__stop_time` |\n| Status = done | MCP: `mcp__knowns__update_task` |\n| Tests pass | Run test suite |\n\n---\n\n## Completion Steps\n\n```json\n// 1. Verify all AC are checked\nmcp__knowns__get_task({ "taskId": "abc123" })\n```\n\n```bash\n# 2. Add implementation notes (use CLI)\nknowns task edit abc123 --notes $\'## Summary\nWhat was done and key decisions.\'\n```\n\n```json\n// 3. Stop timer (REQUIRED!)\nmcp__knowns__stop_time({ "taskId": "abc123" })\n\n// 4. Mark done\nmcp__knowns__update_task({\n "taskId": "abc123",\n "status": "done"\n})\n```\n\n---\n\n## Post-Completion Changes\n\nIf user requests changes after task is done:\n\n```json\n// 1. Reopen task\nmcp__knowns__update_task({\n "taskId": "abc123",\n "status": "in-progress"\n})\n\n// 2. Restart timer\nmcp__knowns__start_time({ "taskId": "abc123" })\n```\n\n```bash\n# 3. Add AC for the fix\nknowns task edit abc123 --ac "Fix: description"\nknowns task edit abc123 --append-notes "Reopened: reason"\n```\n\nThen follow completion steps again.\n\n---\n\n## Checklist\n\n- [ ] All AC checked (CLI `--check-ac`)\n- [ ] Notes added (CLI `--notes`)\n- [ ] Timer stopped (`mcp__knowns__stop_time`)\n- [ ] Tests pass\n- [ ] Status = done (`mcp__knowns__update_task`)\n';
@@ -43592,7 +43664,7 @@ var workflow_completion_default2 = '# Task Completion (MCP)\n\n## Definition of
43592
43664
  var workflow_creation_default2 = '# Task Creation (MCP)\n\n## Before Creating\n\n```json\n// Search for existing tasks first\nmcp__knowns__search_tasks({ "query": "keyword" })\n```\n\n---\n\n## Create Task\n\n```json\nmcp__knowns__create_task({\n "title": "Clear title (WHAT)",\n "description": "Description (WHY). Related: @doc/security-patterns",\n "priority": "medium",\n "labels": ["feature", "auth"]\n})\n```\n\n**Note:** Add acceptance criteria after creation using CLI:\n```bash\nknowns task edit <id> --ac "Outcome 1" --ac "Outcome 2"\n```\n\n---\n\n## Quality Guidelines\n\n### Title\n| Bad | Good |\n|-----|------|\n| Do auth stuff | Add JWT authentication |\n| Fix bug | Fix login timeout |\n\n### Description\nExplain WHY. Include doc refs: `@doc/security-patterns`\n\n### Acceptance Criteria\n**Outcome-focused, NOT implementation steps:**\n\n| Bad | Good |\n|-----|------|\n| Add handleLogin() function | User can login |\n| Use bcrypt | Passwords are hashed |\n| Add try-catch | Errors return proper HTTP codes |\n\n---\n\n## Subtasks\n\n```json\n// Create parent first\nmcp__knowns__create_task({ "title": "Parent task" })\n\n// Then create subtask with parent ID\nmcp__knowns__create_task({\n "title": "Subtask",\n "parent": "parent-task-id"\n})\n```\n\n---\n\n## Anti-Patterns\n\n- Too many AC in one task -> Split into multiple tasks\n- Implementation steps as AC -> Write outcomes instead\n- Skip search -> Always check existing tasks first\n';
43593
43665
 
43594
43666
  // src/templates/guidelines/mcp/workflow-execution.md
43595
- var workflow_execution_default2 = '# Task Execution (MCP)\n\n## Step 1: Take Task\n\n```json\n// Update status and assignee\nmcp__knowns__update_task({\n "taskId": "abc123",\n "status": "in-progress",\n "assignee": "@me"\n})\n\n// Start timer (REQUIRED!)\nmcp__knowns__start_time({ "taskId": "abc123" })\n```\n\n---\n\n## Step 2: Research\n\n```json\n// Read task and follow ALL refs\nmcp__knowns__get_task({ "taskId": "abc123" })\n\n// @.knowns/docs/xxx.md -> read the doc\nmcp__knowns__get_doc({ "path": "xxx" })\n\n// @.knowns/tasks/task-YY -> read the task\nmcp__knowns__get_task({ "taskId": "YY" })\n\n// Search related docs\nmcp__knowns__search_docs({ "query": "keyword" })\n\n// Check similar done tasks\nmcp__knowns__list_tasks({ "status": "done" })\n```\n\n---\n\n## Step 3: Plan (BEFORE coding!)\n\nUse CLI for implementation plan:\n```bash\nknowns task edit <id> --plan $\'1. Research (see @doc/xxx)\n2. Implement\n3. Test\n4. Document\'\n```\n\n**Share plan with user. WAIT for approval before coding.**\n\n---\n\n## Step 4: Implement\n\nUse CLI for checking acceptance criteria:\n```bash\n# Check AC only AFTER work is done\nknowns task edit <id> --check-ac 1\nknowns task edit <id> --append-notes "Done: feature X"\n```\n\n---\n\n## Scope Changes\n\nIf new requirements emerge during work:\n\n```bash\n# Small: Add to current task\nknowns task edit <id> --ac "New requirement"\nknowns task edit <id> --append-notes "Scope updated: reason"\n\n# Large: Ask user first, then create follow-up\n```\n\n```json\nmcp__knowns__create_task({\n "title": "Follow-up: feature",\n "description": "From task <id>"\n})\n```\n\n**Don\'t silently expand scope. Ask user first.**\n\n---\n\n## Key Rules\n\n1. **Plan before code** - Capture approach first\n2. **Wait for approval** - Don\'t start without OK\n3. **Check AC after work** - Not before\n4. **Ask on scope changes** - Don\'t expand silently\n';
43667
+ var workflow_execution_default2 = '# Task Execution (MCP)\n\n## Step 1: Take Task\n\n```json\n// Update status and assignee\nmcp__knowns__update_task({\n "taskId": "abc123",\n "status": "in-progress",\n "assignee": "@me"\n})\n\n// Start timer (REQUIRED!)\nmcp__knowns__start_time({ "taskId": "abc123" })\n```\n\n---\n\n## Step 2: Research\n\n```json\n// Read task and follow ALL refs\nmcp__knowns__get_task({ "taskId": "abc123" })\n\n// @doc/xxx -> read the doc\nmcp__knowns__get_doc({ "path": "xxx" })\n\n// @task-YY -> read the task\nmcp__knowns__get_task({ "taskId": "YY" })\n\n// Search related docs\nmcp__knowns__search_docs({ "query": "keyword" })\n\n// Check similar done tasks\nmcp__knowns__list_tasks({ "status": "done" })\n```\n\n---\n\n## Step 3: Plan (BEFORE coding!)\n\nUse CLI for implementation plan:\n```bash\nknowns task edit <id> --plan $\'1. Research (see @doc/xxx)\n2. Implement\n3. Test\n4. Document\'\n```\n\n**Share plan with user. WAIT for approval before coding.**\n\n---\n\n## Step 4: Implement\n\nUse CLI for checking acceptance criteria:\n```bash\n# Check AC only AFTER work is done\nknowns task edit <id> --check-ac 1\nknowns task edit <id> --append-notes "Done: feature X"\n```\n\n---\n\n## Scope Changes\n\nIf new requirements emerge during work:\n\n```bash\n# Small: Add to current task\nknowns task edit <id> --ac "New requirement"\nknowns task edit <id> --append-notes "Scope updated: reason"\n\n# Large: Ask user first, then create follow-up\n```\n\n```json\nmcp__knowns__create_task({\n "title": "Follow-up: feature",\n "description": "From task <id>"\n})\n```\n\n**Don\'t silently expand scope. Ask user first.**\n\n---\n\n## Key Rules\n\n1. **Plan before code** - Capture approach first\n2. **Wait for approval** - Don\'t start without OK\n3. **Check AC after work** - Not before\n4. **Ask on scope changes** - Don\'t expand silently\n';
43596
43668
 
43597
43669
  // src/templates/guidelines/mcp/index.ts
43598
43670
  var MCP_CORE_RULES = core_rules_default2.trim();
@@ -43687,6 +43759,9 @@ var cli_default = '# Knowns Project\n\nThis project uses **Knowns CLI** for task
43687
43759
  // src/templates/instruction/mcp.md
43688
43760
  var mcp_default = '# Knowns Project\n\nThis project uses **Knowns MCP** tools for task and documentation management.\n\n## Before Starting\n\nCall this MCP tool to get usage guidelines:\n\n```\nmcp__knowns__get_guideline({})\n```\n\nYou MUST call this at session start and follow every rule it returns.\n\n## Context-Specific Guidelines\n\nGet guidelines for specific contexts:\n\n```\n// Full guidelines\nmcp__knowns__get_guideline({ type: "unified" })\n\n// CLI-specific (fallback)\nmcp__knowns__get_guideline({ type: "cli" })\n\n// MCP-specific\nmcp__knowns__get_guideline({ type: "mcp" })\n```\n\n**CLI Fallback:** If MCP tools are unavailable, use CLI commands:\n\n```bash\nknowns agents guideline --full # All guidelines\nknowns agents guideline --stage creation # Task creation\nknowns agents guideline --stage execution # Task execution\nknowns agents guideline --stage completion # Task completion\n```\n\n## Quick Tools\n\n```\n// List tasks\nmcp__knowns__list_tasks({})\n\n// View task\nmcp__knowns__get_task({ taskId: "<id>" })\n\n// List docs\nmcp__knowns__list_docs({})\n\n// View doc\nmcp__knowns__get_doc({ path: "<path>" })\n\n// Search\nmcp__knowns__search_tasks({ query: "keyword" })\nmcp__knowns__search_docs({ query: "keyword" })\n```\n\n**Important:** Always read the guidelines before working on tasks.\n';
43689
43761
 
43762
+ // src/templates/instruction/skills.md
43763
+ var skills_default = '# Knowns Project\n\nThis project uses **Knowns** for task and documentation management with built-in Claude Code skills.\n\n## Available Skills\n\nUse `/knowns.<skill>` to invoke workflows:\n\n| Skill | Description |\n|-------|-------------|\n| `/knowns.init` | Initialize session - read docs, understand context |\n| `/knowns.task <id>` | Full task workflow - research, plan, implement |\n| `/knowns.task.brainstorm` | Explore solutions before implementation |\n| `/knowns.task.reopen` | Reopen completed task, add requirements |\n| `/knowns.task.extract` | Extract patterns from task to docs |\n| `/knowns.doc` | Work with documentation - view, create, update |\n| `/knowns.commit` | Commit with proper format |\n| `/knowns.research` | Research codebase before coding |\n\n## Getting Started\n\n```bash\n# Start a new session\n/knowns.init\n\n# Work on a task\n/knowns.task <task-id>\n\n# Quick commands\nknowns task list --plain\nknowns doc list --plain\nknowns search "query" --plain\n```\n\n## Key Principles\n\n1. **Read docs first** - Understand before implementing\n2. **Plan before coding** - Wait for approval\n3. **Track time** - Always use timer\n4. **Ask when blocked** - Don\'t guess\n';
43764
+
43690
43765
  // src/templates/instruction/index.ts
43691
43766
  var START_MARKER = "<!-- KNOWNS GUIDELINES START -->";
43692
43767
  var END_MARKER = "<!-- KNOWNS GUIDELINES END -->";
@@ -43697,8 +43772,10 @@ ${END_MARKER}`;
43697
43772
  }
43698
43773
  var CLI_TEMPLATE_RAW = cli_default.trim();
43699
43774
  var MCP_TEMPLATE_RAW = mcp_default.trim();
43775
+ var SKILLS_TEMPLATE_RAW = skills_default.trim();
43700
43776
  var CLI_INSTRUCTION = withMarkers(cli_default);
43701
43777
  var MCP_INSTRUCTION = withMarkers(mcp_default);
43778
+ var SKILLS_INSTRUCTION = withMarkers(skills_default);
43702
43779
 
43703
43780
  // src/commands/agents.ts
43704
43781
  var PROJECT_ROOT = process.cwd();
@@ -43713,6 +43790,9 @@ var INSTRUCTION_FILES = [
43713
43790
  }
43714
43791
  ];
43715
43792
  function getGuidelines(type, variant = "general") {
43793
+ if (type === "skills") {
43794
+ return SKILLS_INSTRUCTION;
43795
+ }
43716
43796
  if (variant === "instruction") {
43717
43797
  return type === "mcp" ? MCP_INSTRUCTION : CLI_INSTRUCTION;
43718
43798
  }
@@ -43897,24 +43977,6 @@ async function updateFiles(files, guidelines) {
43897
43977
  }
43898
43978
  console.log();
43899
43979
  }
43900
- var syncCommand = new Command("sync").description("Sync/update all agent instruction files with latest guidelines").option("--type <type>", "Guidelines type: cli or mcp", "cli").option("--minimal", "Use minimal instruction (default: full embedded guidelines)").option("--all", "Update all instruction files (including Gemini, Copilot)").action(async (options2) => {
43901
- try {
43902
- const type = options2.type === "mcp" ? "mcp" : "cli";
43903
- const variant = options2.minimal ? "instruction" : "general";
43904
- const guidelines = getGuidelines(type, variant);
43905
- const filesToUpdate = options2.all ? INSTRUCTION_FILES : INSTRUCTION_FILES.filter((f) => f.selected);
43906
- const variantLabel = variant === "instruction" ? " (minimal)" : " (full)";
43907
- const label = `${type.toUpperCase()}${variantLabel}`;
43908
- console.log(source_default.bold(`
43909
- Syncing agent instructions (${label})...
43910
- `));
43911
- await updateFiles(filesToUpdate, guidelines);
43912
- } catch (error48) {
43913
- console.error(source_default.red("Error:"), error48 instanceof Error ? error48.message : String(error48));
43914
- process.exit(1);
43915
- }
43916
- });
43917
- agentsCommand.addCommand(syncCommand);
43918
43980
  var guidelineCommand = new Command("guideline").description("Output guidelines for AI agents (use this at session start)").option("--cli", "Show CLI-specific guidelines (legacy)").option("--mcp", "Show MCP-specific guidelines (legacy)").option("--full", "Show full guidelines (all sections)").option("--compact", "Show compact guidelines (core + mistakes only)").option("--stage <stage>", "Show guidelines for specific stage: creation, execution, completion").option("--core", "Show core rules only").option("--commands", "Show commands reference only").option("--mistakes", "Show common mistakes only").action(
43919
43981
  async (options2) => {
43920
43982
  try {
@@ -43972,7 +44034,7 @@ function checkGitExists(projectRoot) {
43972
44034
  }
43973
44035
  }
43974
44036
  async function createMcpJsonFile(projectRoot) {
43975
- const { writeFileSync: writeFileSync3, readFileSync: readFileSync4 } = await import("node:fs");
44037
+ const { writeFileSync: writeFileSync4, readFileSync: readFileSync5 } = await import("node:fs");
43976
44038
  const mcpJsonPath = join4(projectRoot, ".mcp.json");
43977
44039
  const mcpConfig = {
43978
44040
  mcpServers: {
@@ -43984,7 +44046,7 @@ async function createMcpJsonFile(projectRoot) {
43984
44046
  };
43985
44047
  if (existsSync2(mcpJsonPath)) {
43986
44048
  try {
43987
- const existing = JSON.parse(readFileSync4(mcpJsonPath, "utf-8"));
44049
+ const existing = JSON.parse(readFileSync5(mcpJsonPath, "utf-8"));
43988
44050
  if (existing?.mcpServers?.knowns) {
43989
44051
  console.log(source_default.gray(" .mcp.json already has knowns configuration"));
43990
44052
  return;
@@ -43993,19 +44055,19 @@ async function createMcpJsonFile(projectRoot) {
43993
44055
  ...existing.mcpServers,
43994
44056
  ...mcpConfig.mcpServers
43995
44057
  };
43996
- writeFileSync3(mcpJsonPath, JSON.stringify(existing, null, " "), "utf-8");
44058
+ writeFileSync4(mcpJsonPath, JSON.stringify(existing, null, " "), "utf-8");
43997
44059
  console.log(source_default.green("\u2713 Added knowns to existing .mcp.json"));
43998
44060
  } catch {
43999
- writeFileSync3(mcpJsonPath, JSON.stringify(mcpConfig, null, " "), "utf-8");
44061
+ writeFileSync4(mcpJsonPath, JSON.stringify(mcpConfig, null, " "), "utf-8");
44000
44062
  console.log(source_default.green("\u2713 Created .mcp.json (replaced invalid file)"));
44001
44063
  }
44002
44064
  } else {
44003
- writeFileSync3(mcpJsonPath, JSON.stringify(mcpConfig, null, " "), "utf-8");
44065
+ writeFileSync4(mcpJsonPath, JSON.stringify(mcpConfig, null, " "), "utf-8");
44004
44066
  console.log(source_default.green("\u2713 Created .mcp.json for Claude Code MCP auto-discovery"));
44005
44067
  }
44006
44068
  }
44007
44069
  async function updateGitignore(projectRoot, mode) {
44008
- const { appendFileSync, readFileSync: readFileSync4, writeFileSync: writeFileSync3 } = await import("node:fs");
44070
+ const { appendFileSync, readFileSync: readFileSync5, writeFileSync: writeFileSync4 } = await import("node:fs");
44009
44071
  const gitignorePath = join4(projectRoot, ".gitignore");
44010
44072
  const patterns = {
44011
44073
  "git-ignored": `
@@ -44022,7 +44084,7 @@ async function updateGitignore(projectRoot, mode) {
44022
44084
  const knownsIgnorePattern = patterns[mode];
44023
44085
  const checkPattern = mode === "none" ? ".knowns/" : ".knowns/*";
44024
44086
  if (existsSync2(gitignorePath)) {
44025
- const content = readFileSync4(gitignorePath, "utf-8");
44087
+ const content = readFileSync5(gitignorePath, "utf-8");
44026
44088
  if (content.includes(checkPattern)) {
44027
44089
  console.log(source_default.gray(" .gitignore already has knowns pattern"));
44028
44090
  return;
@@ -44030,11 +44092,39 @@ async function updateGitignore(projectRoot, mode) {
44030
44092
  appendFileSync(gitignorePath, knownsIgnorePattern);
44031
44093
  console.log(source_default.green("\u2713 Updated .gitignore with knowns pattern"));
44032
44094
  } else {
44033
- writeFileSync3(gitignorePath, `${knownsIgnorePattern.trim()}
44095
+ writeFileSync4(gitignorePath, `${knownsIgnorePattern.trim()}
44034
44096
  `, "utf-8");
44035
44097
  console.log(source_default.green("\u2713 Created .gitignore with knowns pattern"));
44036
44098
  }
44037
44099
  }
44100
+ async function createClaudeSkills(projectRoot) {
44101
+ const { mkdirSync: mkdirSync2, writeFileSync: writeFileSync4 } = await import("node:fs");
44102
+ const skillsDir = join4(projectRoot, ".claude", "skills");
44103
+ if (!existsSync2(skillsDir)) {
44104
+ mkdirSync2(skillsDir, { recursive: true });
44105
+ }
44106
+ let createdCount = 0;
44107
+ let skippedCount = 0;
44108
+ for (const skill of SKILLS) {
44109
+ const skillFolder = join4(skillsDir, skill.folderName);
44110
+ const skillFile = join4(skillFolder, "SKILL.md");
44111
+ if (existsSync2(skillFile)) {
44112
+ skippedCount++;
44113
+ continue;
44114
+ }
44115
+ if (!existsSync2(skillFolder)) {
44116
+ mkdirSync2(skillFolder, { recursive: true });
44117
+ }
44118
+ writeFileSync4(skillFile, skill.content, "utf-8");
44119
+ createdCount++;
44120
+ }
44121
+ if (createdCount > 0) {
44122
+ console.log(source_default.green(`\u2713 Created ${createdCount} Claude Code skills in .claude/skills/`));
44123
+ }
44124
+ if (skippedCount > 0) {
44125
+ console.log(source_default.gray(` Skipped ${skippedCount} existing skills`));
44126
+ }
44127
+ }
44038
44128
  async function runWizard() {
44039
44129
  const projectRoot = process.cwd();
44040
44130
  const defaultName = basename(projectRoot);
@@ -44081,9 +44171,14 @@ async function runWizard() {
44081
44171
  message: "AI Guidelines type",
44082
44172
  choices: [
44083
44173
  {
44084
- title: "CLI",
44174
+ title: "Skills (recommended)",
44175
+ value: "skills",
44176
+ description: "Minimal CLAUDE.md + built-in /knowns:* skills"
44177
+ },
44178
+ {
44179
+ title: "CLI (full guidelines)",
44085
44180
  value: "cli",
44086
- description: "Use CLI commands (knowns task edit, knowns doc view)"
44181
+ description: "Full CLI guidelines embedded in CLAUDE.md"
44087
44182
  },
44088
44183
  {
44089
44184
  title: "MCP",
@@ -44092,7 +44187,7 @@ async function runWizard() {
44092
44187
  }
44093
44188
  ],
44094
44189
  initial: 0
44095
- // CLI
44190
+ // Skills
44096
44191
  },
44097
44192
  {
44098
44193
  type: "multiselect",
@@ -44123,7 +44218,7 @@ async function runWizard() {
44123
44218
  defaultLabels: [],
44124
44219
  timeFormat: "24h",
44125
44220
  gitTrackingMode: response.gitTrackingMode || "git-tracked",
44126
- guidelinesType: response.guidelinesType || "cli",
44221
+ guidelinesType: response.guidelinesType || "skills",
44127
44222
  agentFiles: response.agentFiles || []
44128
44223
  };
44129
44224
  }
@@ -44157,7 +44252,7 @@ var initCommand = new Command("init").description("Initialize .knowns/ folder in
44157
44252
  defaultLabels: [],
44158
44253
  timeFormat: "24h",
44159
44254
  gitTrackingMode: "git-tracked",
44160
- guidelinesType: "cli",
44255
+ guidelinesType: "skills",
44161
44256
  agentFiles: INSTRUCTION_FILES.filter((f) => f.selected)
44162
44257
  };
44163
44258
  }
@@ -44176,6 +44271,7 @@ var initCommand = new Command("init").description("Initialize .knowns/ folder in
44176
44271
  });
44177
44272
  console.log();
44178
44273
  console.log(source_default.green(`\u2713 Project initialized: ${project.name}`));
44274
+ await createClaudeSkills(projectRoot);
44179
44275
  if (config2.agentFiles.length > 0) {
44180
44276
  const guidelines = getGuidelines(config2.guidelinesType);
44181
44277
  for (const file3 of config2.agentFiles) {
@@ -44289,60 +44385,13 @@ function findProjectRoot(startPath = process.cwd()) {
44289
44385
  }
44290
44386
 
44291
44387
  // src/utils/mention-refs.ts
44292
- var TASK_MENTION_REGEX = /@task-(\d+)/g;
44293
- var DOC_MENTION_REGEX = /@docs?\/([^\s|)]+)/g;
44294
- var OUTPUT_TASK_REGEX = /@\.knowns\/tasks\/task-(\d+)(?:\s*-\s*[^@\n]+?\.md|\.md)/g;
44388
+ var OUTPUT_TASK_REGEX = /@\.knowns\/tasks\/task-([a-zA-Z0-9]+)(?:\s*-\s*[^@\n]+?\.md|\.md)/g;
44295
44389
  var OUTPUT_DOC_REGEX = /@\.knowns\/docs\/([^\s@]+?)\.md(?:\s*-\s*[^@\n]+)?/g;
44296
- function sanitizeTitle(title) {
44297
- return title.replace(/[<>:"/\\|?*]/g, "").replace(/\s+/g, " ").trim().slice(0, 50);
44298
- }
44299
- function transformTaskMention(taskId, tasks) {
44300
- const task = tasks.get(taskId);
44301
- if (task) {
44302
- const sanitizedTitle = sanitizeTitle(task.title);
44303
- return `@.knowns/tasks/task-${taskId} - ${sanitizedTitle}.md`;
44304
- }
44305
- return `@.knowns/tasks/task-${taskId}.md`;
44306
- }
44307
- function transformDocMention(docPath) {
44308
- const normalizedPath = docPath.endsWith(".md") ? docPath : `${docPath}.md`;
44309
- return `@.knowns/docs/${normalizedPath}`;
44310
- }
44311
- function transformMentionsToRefs(text, tasks) {
44312
- const codeBlocks = [];
44313
- const inlineCodes = [];
44314
- let result = text.replace(/```[\s\S]*?```/g, (match) => {
44315
- const index = codeBlocks.length;
44316
- codeBlocks.push(match);
44317
- return `__CODE_BLOCK_${index}__`;
44318
- });
44319
- result = result.replace(/`[^`]+`/g, (match) => {
44320
- const index = inlineCodes.length;
44321
- inlineCodes.push(match);
44322
- return `__INLINE_CODE_${index}__`;
44323
- });
44324
- result = result.replace(TASK_MENTION_REGEX, (match, taskId) => {
44325
- return transformTaskMention(taskId, tasks);
44326
- });
44327
- result = result.replace(DOC_MENTION_REGEX, (match, docPath) => {
44328
- return transformDocMention(docPath);
44329
- });
44330
- result = result.replace(/__INLINE_CODE_(\d+)__/g, (_, index) => inlineCodes[Number.parseInt(index)]);
44331
- result = result.replace(/__CODE_BLOCK_(\d+)__/g, (_, index) => codeBlocks[Number.parseInt(index)]);
44332
- return result;
44333
- }
44334
- function buildTaskMap(tasks) {
44335
- const map2 = /* @__PURE__ */ new Map();
44336
- for (const task of tasks) {
44337
- map2.set(task.id, task);
44338
- }
44339
- return map2;
44340
- }
44341
44390
  function normalizeRefs(text) {
44342
44391
  let result = text;
44343
44392
  result = parseEscapeSequences(result);
44344
- result = result.replace(new RegExp(OUTPUT_TASK_REGEX.source, "g"), (match, taskId) => `@task-${taskId}`);
44345
- result = result.replace(new RegExp(OUTPUT_DOC_REGEX.source, "g"), (match, docPath) => `@doc/${docPath}`);
44393
+ result = result.replace(new RegExp(OUTPUT_TASK_REGEX.source, "g"), (_match, taskId) => `@task-${taskId}`);
44394
+ result = result.replace(new RegExp(OUTPUT_DOC_REGEX.source, "g"), (_match, docPath) => `@doc/${docPath}`);
44346
44395
  return result;
44347
44396
  }
44348
44397
  function parseEscapeSequences(text) {
@@ -44854,9 +44903,6 @@ async function formatTask(task, fileStore2, plain = false) {
44854
44903
  const border = "-".repeat(50);
44855
44904
  const titleBorder = "=".repeat(50);
44856
44905
  const output2 = [];
44857
- const allTasks = await fileStore2.getAllTasks();
44858
- const taskMap = buildTaskMap(allTasks);
44859
- const transformText = (text) => transformMentionsToRefs(text, taskMap);
44860
44906
  const projectRoot2 = findProjectRoot();
44861
44907
  if (projectRoot2) {
44862
44908
  const filename = `task-${task.id} - ${task.title.replace(/[^a-z0-9]+/gi, "-")}`;
@@ -44908,7 +44954,7 @@ async function formatTask(task, fileStore2, plain = false) {
44908
44954
  if (task.description) {
44909
44955
  output2.push("Description:");
44910
44956
  output2.push(border);
44911
- output2.push(transformText(task.description));
44957
+ output2.push(task.description);
44912
44958
  output2.push("");
44913
44959
  }
44914
44960
  if (task.acceptanceCriteria.length > 0) {
@@ -44916,20 +44962,20 @@ async function formatTask(task, fileStore2, plain = false) {
44916
44962
  output2.push(border);
44917
44963
  for (const [i, ac] of task.acceptanceCriteria.entries()) {
44918
44964
  const checkbox = ac.completed ? "[x]" : "[ ]";
44919
- output2.push(`- ${checkbox} #${i + 1} ${transformText(ac.text)}`);
44965
+ output2.push(`- ${checkbox} #${i + 1} ${ac.text}`);
44920
44966
  }
44921
44967
  output2.push("");
44922
44968
  }
44923
44969
  if (task.implementationPlan) {
44924
44970
  output2.push("Implementation Plan:");
44925
44971
  output2.push(border);
44926
- output2.push(transformText(task.implementationPlan));
44972
+ output2.push(task.implementationPlan);
44927
44973
  output2.push("");
44928
44974
  }
44929
44975
  if (task.implementationNotes) {
44930
44976
  output2.push("Implementation Notes:");
44931
44977
  output2.push(border);
44932
- output2.push(transformText(task.implementationNotes));
44978
+ output2.push(task.implementationNotes);
44933
44979
  output2.push("");
44934
44980
  }
44935
44981
  if (projectRoot2) {
@@ -47934,6 +47980,13 @@ function extractSection(markdown, sectionTitle) {
47934
47980
  }
47935
47981
  return lines.slice(startLine, endLine).join("\n").trim();
47936
47982
  }
47983
+ function extractSectionByIndex(markdown, index) {
47984
+ const toc = extractToc(markdown);
47985
+ if (index < 1 || index > toc.length) {
47986
+ return null;
47987
+ }
47988
+ return extractSection(markdown, toc[index - 1].title);
47989
+ }
47937
47990
  function replaceSection(markdown, sectionTitle, newContent) {
47938
47991
  const lines = markdown.split("\n");
47939
47992
  const normalizedTarget = normalizeTitle(sectionTitle);
@@ -47966,9 +48019,37 @@ function replaceSection(markdown, sectionTitle, newContent) {
47966
48019
  }
47967
48020
  const beforeSection = lines.slice(0, startLine);
47968
48021
  const afterSection = lines.slice(endLine);
47969
- const newSection = `${originalHeading}
48022
+ const trimmedContent = newContent.trim();
48023
+ const contentStartsWithHeading = /^#{1,6}\s+/.test(trimmedContent);
48024
+ const newSection = contentStartsWithHeading ? trimmedContent : `${originalHeading}
48025
+
48026
+ ${trimmedContent}`;
48027
+ return [...beforeSection, newSection, ...afterSection].join("\n");
48028
+ }
48029
+ function replaceSectionByIndex(markdown, index, newContent) {
48030
+ const toc = extractToc(markdown);
48031
+ if (index < 1 || index > toc.length) {
48032
+ return null;
48033
+ }
48034
+ const lines = markdown.split("\n");
48035
+ const targetEntry = toc[index - 1];
48036
+ const startLine = targetEntry.line - 1;
48037
+ const startLevel = targetEntry.level;
48038
+ const originalHeading = lines[startLine];
48039
+ let endLine = lines.length;
48040
+ for (let i = index; i < toc.length; i++) {
48041
+ if (toc[i].level <= startLevel) {
48042
+ endLine = toc[i].line - 1;
48043
+ break;
48044
+ }
48045
+ }
48046
+ const beforeSection = lines.slice(0, startLine);
48047
+ const afterSection = lines.slice(endLine);
48048
+ const trimmedContent = newContent.trim();
48049
+ const contentStartsWithHeading = /^#{1,6}\s+/.test(trimmedContent);
48050
+ const newSection = contentStartsWithHeading ? trimmedContent : `${originalHeading}
47970
48051
 
47971
- ${newContent.trim()}`;
48052
+ ${trimmedContent}`;
47972
48053
  return [...beforeSection, newSection, ...afterSection].join("\n");
47973
48054
  }
47974
48055
  function slugify(title) {
@@ -48147,11 +48228,13 @@ var listCommand2 = new Command("list").description("List all documentation files
48147
48228
  }
48148
48229
  const docs = [];
48149
48230
  for (const file3 of mdFiles) {
48150
- const content = await readFile11(join17(DOCS_DIR, file3), "utf-8");
48151
- const { data } = (0, import_gray_matter6.default)(content);
48231
+ const fileContent = await readFile11(join17(DOCS_DIR, file3), "utf-8");
48232
+ const { data, content } = (0, import_gray_matter6.default)(fileContent);
48233
+ const stats = calculateDocStats(content);
48152
48234
  docs.push({
48153
48235
  filename: file3,
48154
- metadata: data
48236
+ metadata: data,
48237
+ tokens: stats.estimatedTokens
48155
48238
  });
48156
48239
  }
48157
48240
  let filteredDocs = docs;
@@ -48177,7 +48260,8 @@ var listCommand2 = new Command("list").description("List all documentation files
48177
48260
  if (parts.length === 1) {
48178
48261
  rootDocs.push({
48179
48262
  name: parts[0].replace(/\.md$/, ""),
48180
- title: doc.metadata.title
48263
+ title: doc.metadata.title,
48264
+ tokens: doc.tokens
48181
48265
  });
48182
48266
  } else {
48183
48267
  const folder = parts.slice(0, -1).join("/");
@@ -48185,7 +48269,7 @@ var listCommand2 = new Command("list").description("List all documentation files
48185
48269
  if (!folders.has(folder)) {
48186
48270
  folders.set(folder, []);
48187
48271
  }
48188
- folders.get(folder)?.push({ name, title: doc.metadata.title });
48272
+ folders.get(folder)?.push({ name, title: doc.metadata.title, tokens: doc.tokens });
48189
48273
  }
48190
48274
  }
48191
48275
  const sortedFolders = Array.from(folders.keys()).sort();
@@ -48193,13 +48277,13 @@ var listCommand2 = new Command("list").description("List all documentation files
48193
48277
  console.log(`${folder}/`);
48194
48278
  const docs2 = folders.get(folder)?.sort((a, b) => a.name.localeCompare(b.name));
48195
48279
  for (const doc of docs2) {
48196
- console.log(` ${doc.name} - ${doc.title}`);
48280
+ console.log(` ${doc.name} - ${doc.title} (~${doc.tokens} tokens)`);
48197
48281
  }
48198
48282
  }
48199
48283
  if (rootDocs.length > 0) {
48200
48284
  rootDocs.sort((a, b) => a.name.localeCompare(b.name));
48201
48285
  for (const doc of rootDocs) {
48202
- console.log(`${doc.name} - ${doc.title}`);
48286
+ console.log(`${doc.name} - ${doc.title} (~${doc.tokens} tokens)`);
48203
48287
  }
48204
48288
  }
48205
48289
  } else {
@@ -48254,7 +48338,7 @@ Documentation (${filteredDocs.length})
48254
48338
  process.exit(1);
48255
48339
  }
48256
48340
  });
48257
- var viewCommand2 = new Command("view").description("View a documentation file").argument("<name>", "Document name (filename or title or path)").option("--plain", "Plain text output for AI").option("--info", "Show document stats (size, tokens, headings) without content").option("--toc", "Show table of contents only").option("--section <title>", "Show specific section by heading title or number (e.g., '2. Overview' or '2')").action(
48341
+ var viewCommand2 = new Command("view").description("View a documentation file").argument("<name>", "Document name (filename or title or path)").option("--plain", "Plain text output for AI").option("--info", "Show document stats (size, tokens, headings) without content").option("--toc", "Show table of contents only").option("--section <title>", "Show specific section by heading title or number (e.g., '2. Overview' or '2')").option("--smart", "Smart mode: auto-return full content if small, or stats+TOC if large (>2000 tokens)").action(
48258
48342
  async (name, options2) => {
48259
48343
  try {
48260
48344
  await ensureDocsDir();
@@ -48284,6 +48368,45 @@ var viewCommand2 = new Command("view").description("View a documentation file").
48284
48368
  const fileContent = await readFile11(filepath, "utf-8");
48285
48369
  const { data, content } = (0, import_gray_matter6.default)(fileContent);
48286
48370
  const metadata = data;
48371
+ if (options2.smart) {
48372
+ const stats = calculateDocStats(content);
48373
+ const SMART_THRESHOLD = 2e3;
48374
+ if (stats.estimatedTokens <= SMART_THRESHOLD) {
48375
+ } else {
48376
+ const toc = extractToc(content);
48377
+ if (options2.plain) {
48378
+ console.log(`Document: ${metadata.title}`);
48379
+ console.log("=".repeat(50));
48380
+ console.log();
48381
+ console.log(
48382
+ `Size: ${stats.chars.toLocaleString()} chars (~${stats.estimatedTokens.toLocaleString()} tokens)`
48383
+ );
48384
+ console.log(`Headings: ${stats.headingCount}`);
48385
+ console.log();
48386
+ console.log("Table of Contents:");
48387
+ console.log("-".repeat(50));
48388
+ toc.forEach((entry, index) => {
48389
+ const indent = " ".repeat(entry.level - 1);
48390
+ console.log(`${indent}${index + 1}. ${entry.title}`);
48391
+ });
48392
+ console.log();
48393
+ console.log("Document is large. Use --section <number> to read a specific section.");
48394
+ } else {
48395
+ console.log(source_default.bold(`
48396
+ \u{1F4C4} ${metadata.title} (Smart Mode)
48397
+ `));
48398
+ console.log(
48399
+ `Size: ${source_default.cyan(stats.chars.toLocaleString())} chars (~${source_default.yellow(stats.estimatedTokens.toLocaleString())} tokens)`
48400
+ );
48401
+ console.log();
48402
+ console.log(source_default.bold("Table of Contents:"));
48403
+ console.log(formatToc(toc));
48404
+ console.log();
48405
+ console.log(source_default.yellow("\u26A0 Document is large. Use --section <number> to read a specific section."));
48406
+ }
48407
+ return;
48408
+ }
48409
+ }
48287
48410
  if (options2.info) {
48288
48411
  const stats = calculateDocStats(content);
48289
48412
  if (options2.plain) {
@@ -48336,7 +48459,8 @@ var viewCommand2 = new Command("view").description("View a documentation file").
48336
48459
  return;
48337
48460
  }
48338
48461
  if (options2.section) {
48339
- const sectionContent = extractSection(content, options2.section);
48462
+ const sectionIndex = /^\d+$/.test(options2.section) ? Number.parseInt(options2.section, 10) : null;
48463
+ const sectionContent = sectionIndex !== null ? extractSectionByIndex(content, sectionIndex) : extractSection(content, options2.section);
48340
48464
  if (!sectionContent) {
48341
48465
  console.error(
48342
48466
  options2.plain ? `Section not found: ${options2.section}` : source_default.red(`\u2717 Section not found: ${options2.section}`)
@@ -48411,13 +48535,6 @@ var viewCommand2 = new Command("view").description("View a documentation file").
48411
48535
  for (const { original, resolved } of linksToAdd) {
48412
48536
  enhancedContent = enhancedContent.replace(original, resolved);
48413
48537
  }
48414
- const knownProjectRoot = findProjectRoot();
48415
- if (knownProjectRoot) {
48416
- const fileStore2 = new FileStore(knownProjectRoot);
48417
- const allTasks = await fileStore2.getAllTasks();
48418
- const taskMap = buildTaskMap(allTasks);
48419
- enhancedContent = transformMentionsToRefs(enhancedContent, taskMap);
48420
- }
48421
48538
  console.log(enhancedContent);
48422
48539
  } else {
48423
48540
  console.log(source_default.bold(`
@@ -48500,7 +48617,8 @@ var editCommand2 = new Command("edit").description("Edit a documentation file (m
48500
48617
  ${normalizeRefs(fileData)}`;
48501
48618
  sourceFile = options2.appendFile;
48502
48619
  } else if (options2.section && options2.content) {
48503
- const result = replaceSection(content, options2.section, normalizeRefs(options2.content));
48620
+ const sectionIndex = /^\d+$/.test(options2.section) ? Number.parseInt(options2.section, 10) : null;
48621
+ const result = sectionIndex !== null ? replaceSectionByIndex(content, sectionIndex, normalizeRefs(options2.content)) : replaceSection(content, options2.section, normalizeRefs(options2.content));
48504
48622
  if (!result) {
48505
48623
  console.error(
48506
48624
  options2.plain ? `Section not found: ${options2.section}` : source_default.red(`\u2717 Section not found: ${options2.section}`)
@@ -48825,7 +48943,7 @@ ${afterSection.trimStart()}`;
48825
48943
  process.exit(1);
48826
48944
  }
48827
48945
  });
48828
- var docCommand = new Command("doc").description("Manage documentation").argument("[name]", "Document name (shorthand for 'doc view <name>')").option("--plain", "Plain text output for AI").option("--info", "Show document stats (size, tokens, headings) without content").option("--toc", "Show table of contents only").option("--section <title>", "Show specific section by heading title or number").enablePositionalOptions().action(
48946
+ var docCommand = new Command("doc").description("Manage documentation").argument("[name]", "Document name (shorthand for 'doc view <name>')").option("--plain", "Plain text output for AI").option("--info", "Show document stats (size, tokens, headings) without content").option("--toc", "Show table of contents only").option("--section <title>", "Show specific section by heading title or number").option("--smart", "Smart mode: auto-return full content if small, or stats+TOC if large (>2000 tokens)").enablePositionalOptions().action(
48829
48947
  async (name, options2) => {
48830
48948
  if (!name) {
48831
48949
  docCommand.help();
@@ -48841,6 +48959,45 @@ var docCommand = new Command("doc").description("Manage documentation").argument
48841
48959
  const fileContent = await readFile11(filepath, "utf-8");
48842
48960
  const { data, content } = (0, import_gray_matter6.default)(fileContent);
48843
48961
  const metadata = data;
48962
+ if (options2.smart) {
48963
+ const stats = calculateDocStats(content);
48964
+ const SMART_THRESHOLD = 2e3;
48965
+ if (stats.estimatedTokens <= SMART_THRESHOLD) {
48966
+ } else {
48967
+ const toc = extractToc(content);
48968
+ if (options2.plain) {
48969
+ console.log(`Document: ${metadata.title}`);
48970
+ console.log("=".repeat(50));
48971
+ console.log();
48972
+ console.log(
48973
+ `Size: ${stats.chars.toLocaleString()} chars (~${stats.estimatedTokens.toLocaleString()} tokens)`
48974
+ );
48975
+ console.log(`Headings: ${stats.headingCount}`);
48976
+ console.log();
48977
+ console.log("Table of Contents:");
48978
+ console.log("-".repeat(50));
48979
+ toc.forEach((entry, index) => {
48980
+ const indent = " ".repeat(entry.level - 1);
48981
+ console.log(`${indent}${index + 1}. ${entry.title}`);
48982
+ });
48983
+ console.log();
48984
+ console.log("Document is large. Use --section <number> to read a specific section.");
48985
+ } else {
48986
+ console.log(source_default.bold(`
48987
+ \u{1F4C4} ${metadata.title} (Smart Mode)
48988
+ `));
48989
+ console.log(
48990
+ `Size: ${source_default.cyan(stats.chars.toLocaleString())} chars (~${source_default.yellow(stats.estimatedTokens.toLocaleString())} tokens)`
48991
+ );
48992
+ console.log();
48993
+ console.log(source_default.bold("Table of Contents:"));
48994
+ console.log(formatToc(toc));
48995
+ console.log();
48996
+ console.log(source_default.yellow("\u26A0 Document is large. Use --section <number> to read a specific section."));
48997
+ }
48998
+ return;
48999
+ }
49000
+ }
48844
49001
  if (options2.info) {
48845
49002
  const stats = calculateDocStats(content);
48846
49003
  if (options2.plain) {
@@ -48893,7 +49050,8 @@ var docCommand = new Command("doc").description("Manage documentation").argument
48893
49050
  return;
48894
49051
  }
48895
49052
  if (options2.section) {
48896
- const sectionContent = extractSection(content, options2.section);
49053
+ const sectionIndex = /^\d+$/.test(options2.section) ? Number.parseInt(options2.section, 10) : null;
49054
+ const sectionContent = sectionIndex !== null ? extractSectionByIndex(content, sectionIndex) : extractSection(content, options2.section);
48897
49055
  if (!sectionContent) {
48898
49056
  console.error(
48899
49057
  options2.plain ? `Section not found: ${options2.section}` : source_default.red(`\u2717 Section not found: ${options2.section}`)
@@ -48968,13 +49126,6 @@ var docCommand = new Command("doc").description("Manage documentation").argument
48968
49126
  for (const { original, resolved: resolved2 } of linksToAdd) {
48969
49127
  enhancedContent = enhancedContent.replace(original, resolved2);
48970
49128
  }
48971
- const knownProjectRoot = findProjectRoot();
48972
- if (knownProjectRoot) {
48973
- const fileStore2 = new FileStore(knownProjectRoot);
48974
- const allTasks = await fileStore2.getAllTasks();
48975
- const taskMap = buildTaskMap(allTasks);
48976
- enhancedContent = transformMentionsToRefs(enhancedContent, taskMap);
48977
- }
48978
49129
  console.log(enhancedContent);
48979
49130
  } else {
48980
49131
  console.log(source_default.bold(`
@@ -62987,14 +63138,135 @@ var resetCommand = new Command("reset").description("Reset configuration to defa
62987
63138
  });
62988
63139
  var configCommand = new Command("config").description("Manage configuration settings").addCommand(listCommand3).addCommand(getCommand).addCommand(setCommand).addCommand(resetCommand);
62989
63140
 
63141
+ // src/commands/sync.ts
63142
+ import { existsSync as existsSync16, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
63143
+ import { join as join19 } from "node:path";
63144
+ var PROJECT_ROOT2 = process.cwd();
63145
+ async function syncSkills(options2) {
63146
+ const skillsDir = join19(PROJECT_ROOT2, ".claude", "skills");
63147
+ if (!existsSync16(skillsDir)) {
63148
+ mkdirSync(skillsDir, { recursive: true });
63149
+ console.log(source_default.green("\u2713 Created .claude/skills/"));
63150
+ }
63151
+ let created = 0;
63152
+ let updated = 0;
63153
+ let skipped = 0;
63154
+ for (const skill of SKILLS) {
63155
+ const skillFolder = join19(skillsDir, skill.folderName);
63156
+ const skillFile = join19(skillFolder, "SKILL.md");
63157
+ if (existsSync16(skillFile)) {
63158
+ if (options2.force) {
63159
+ const existing = readFileSync2(skillFile, "utf-8");
63160
+ if (existing.trim() !== skill.content.trim()) {
63161
+ writeFileSync(skillFile, skill.content, "utf-8");
63162
+ console.log(source_default.green(`\u2713 Updated: ${skill.name}`));
63163
+ updated++;
63164
+ } else {
63165
+ console.log(source_default.gray(` Unchanged: ${skill.name}`));
63166
+ skipped++;
63167
+ }
63168
+ } else {
63169
+ console.log(source_default.gray(` Skipped: ${skill.name} (use --force to update)`));
63170
+ skipped++;
63171
+ }
63172
+ } else {
63173
+ if (!existsSync16(skillFolder)) {
63174
+ mkdirSync(skillFolder, { recursive: true });
63175
+ }
63176
+ writeFileSync(skillFile, skill.content, "utf-8");
63177
+ console.log(source_default.green(`\u2713 Created: ${skill.name}`));
63178
+ created++;
63179
+ }
63180
+ }
63181
+ return { created, updated, skipped };
63182
+ }
63183
+ async function syncAgents(options2) {
63184
+ const type = options2.type === "mcp" ? "mcp" : "cli";
63185
+ const guidelines = getGuidelines(type);
63186
+ const filesToUpdate = options2.all ? INSTRUCTION_FILES : INSTRUCTION_FILES.filter((f) => f.selected);
63187
+ let created = 0;
63188
+ let updated = 0;
63189
+ let skipped = 0;
63190
+ for (const file3 of filesToUpdate) {
63191
+ try {
63192
+ const result = await updateInstructionFile(file3.path, guidelines);
63193
+ if (result.success) {
63194
+ if (result.action === "created") {
63195
+ console.log(source_default.green(`\u2713 Created: ${file3.path}`));
63196
+ created++;
63197
+ } else if (result.action === "appended") {
63198
+ console.log(source_default.cyan(`\u2713 Appended: ${file3.path}`));
63199
+ updated++;
63200
+ } else {
63201
+ console.log(source_default.green(`\u2713 Updated: ${file3.path}`));
63202
+ updated++;
63203
+ }
63204
+ }
63205
+ } catch (error48) {
63206
+ console.log(source_default.gray(` Skipped: ${file3.path}`));
63207
+ skipped++;
63208
+ }
63209
+ }
63210
+ return { created, updated, skipped };
63211
+ }
63212
+ function printSummary(label, stats) {
63213
+ console.log(source_default.bold(`
63214
+ ${label}:`));
63215
+ if (stats.created > 0) console.log(source_default.green(` Created: ${stats.created}`));
63216
+ if (stats.updated > 0) console.log(source_default.green(` Updated: ${stats.updated}`));
63217
+ if (stats.skipped > 0) console.log(source_default.gray(` Skipped: ${stats.skipped}`));
63218
+ }
63219
+ var syncCommand = new Command("sync").description("Sync skills and agent instruction files").enablePositionalOptions().option("-f, --force", "Force overwrite existing files").option("--type <type>", "Guidelines type for agents: cli or mcp", "cli").option("--all", "Update all agent files (including Gemini, Copilot)").action(async (options2) => {
63220
+ try {
63221
+ console.log(source_default.bold("\nSyncing all...\n"));
63222
+ console.log(source_default.cyan("Skills:"));
63223
+ const skillStats = await syncSkills(options2);
63224
+ console.log(source_default.cyan("\nAgent files:"));
63225
+ const agentStats = await syncAgents(options2);
63226
+ printSummary("Skills", skillStats);
63227
+ printSummary("Agents", agentStats);
63228
+ console.log();
63229
+ } catch (error48) {
63230
+ console.error(source_default.red("Error:"), error48 instanceof Error ? error48.message : String(error48));
63231
+ process.exit(1);
63232
+ }
63233
+ });
63234
+ var skillsSubcommand = new Command("skills").description("Sync Claude Code skills only").option("-f, --force", "Force overwrite existing skills").action(async (options2) => {
63235
+ try {
63236
+ console.log(source_default.bold("\nSyncing skills...\n"));
63237
+ const stats = await syncSkills({ force: options2.force });
63238
+ printSummary("Summary", stats);
63239
+ console.log();
63240
+ } catch (error48) {
63241
+ console.error(source_default.red("Error:"), error48 instanceof Error ? error48.message : String(error48));
63242
+ process.exit(1);
63243
+ }
63244
+ });
63245
+ var agentSubcommand = new Command("agent").description("Sync agent instruction files only (CLAUDE.md, AGENTS.md, etc.)").option("--force", "Force overwrite existing files").option("--type <type>", "Guidelines type: cli or mcp", "cli").option("--all", "Update all agent files (including Gemini, Copilot)").action(async (options2) => {
63246
+ try {
63247
+ const type = options2.type === "mcp" ? "mcp" : "cli";
63248
+ console.log(source_default.bold(`
63249
+ Syncing agent files (${type.toUpperCase()})...
63250
+ `));
63251
+ const stats = await syncAgents(options2);
63252
+ printSummary("Summary", stats);
63253
+ console.log();
63254
+ } catch (error48) {
63255
+ console.error(source_default.red("Error:"), error48 instanceof Error ? error48.message : String(error48));
63256
+ process.exit(1);
63257
+ }
63258
+ });
63259
+ syncCommand.addCommand(skillsSubcommand);
63260
+ syncCommand.addCommand(agentSubcommand);
63261
+
62990
63262
  // src/commands/mcp.ts
62991
- import { existsSync as existsSync18, readFileSync as readFileSync2, writeFileSync } from "node:fs";
62992
- import { join as join22 } from "node:path";
63263
+ import { existsSync as existsSync19, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
63264
+ import { join as join23 } from "node:path";
62993
63265
 
62994
63266
  // src/mcp/server.ts
62995
- import { existsSync as existsSync17 } from "node:fs";
63267
+ import { existsSync as existsSync18 } from "node:fs";
62996
63268
  import { readFile as readFile15 } from "node:fs/promises";
62997
- import { join as join21 } from "node:path";
63269
+ import { join as join22 } from "node:path";
62998
63270
 
62999
63271
  // node_modules/zod/v3/helpers/util.js
63000
63272
  var util;
@@ -70058,7 +70330,7 @@ var import_gray_matter9 = __toESM(require_gray_matter(), 1);
70058
70330
 
70059
70331
  // src/mcp/utils.ts
70060
70332
  import { readFile as readFile13 } from "node:fs/promises";
70061
- import { join as join19 } from "node:path";
70333
+ import { join as join20 } from "node:path";
70062
70334
  var import_gray_matter7 = __toESM(require_gray_matter(), 1);
70063
70335
  function parseDuration2(durationStr) {
70064
70336
  let totalSeconds = 0;
@@ -70091,7 +70363,7 @@ function formatDuration2(seconds) {
70091
70363
  }
70092
70364
  async function fetchLinkedDocs(task) {
70093
70365
  const projectRoot = process.cwd();
70094
- const docsDir = join19(projectRoot, ".knowns", "docs");
70366
+ const docsDir = join20(projectRoot, ".knowns", "docs");
70095
70367
  const allContent = [task.description || "", task.implementationPlan || "", task.implementationNotes || ""].join("\n");
70096
70368
  const docRefs = resolveDocReferences(allContent, projectRoot);
70097
70369
  const linkedDocs = [];
@@ -70099,7 +70371,7 @@ async function fetchLinkedDocs(task) {
70099
70371
  if (!ref.exists) continue;
70100
70372
  try {
70101
70373
  const filename = ref.resolvedPath.replace("@.knowns/docs/", "");
70102
- const filepath = join19(docsDir, filename);
70374
+ const filepath = join20(docsDir, filename);
70103
70375
  const fileContent = await readFile13(filepath, "utf-8");
70104
70376
  const { data, content } = (0, import_gray_matter7.default)(fileContent);
70105
70377
  linkedDocs.push({
@@ -70662,11 +70934,11 @@ async function handleGetBoard(fileStore2) {
70662
70934
  }
70663
70935
 
70664
70936
  // src/mcp/handlers/doc.ts
70665
- import { existsSync as existsSync16 } from "node:fs";
70937
+ import { existsSync as existsSync17 } from "node:fs";
70666
70938
  import { mkdir as mkdir9, readFile as readFile14, readdir as readdir6, writeFile as writeFile10 } from "node:fs/promises";
70667
- import { join as join20 } from "node:path";
70939
+ import { join as join21 } from "node:path";
70668
70940
  var import_gray_matter8 = __toESM(require_gray_matter(), 1);
70669
- var DOCS_DIR2 = join20(process.cwd(), ".knowns", "docs");
70941
+ var DOCS_DIR2 = join21(process.cwd(), ".knowns", "docs");
70670
70942
  var listDocsSchema = external_exports.object({
70671
70943
  tag: external_exports.string().optional()
70672
70944
  });
@@ -70677,8 +70949,10 @@ var getDocSchema = external_exports.object({
70677
70949
  // Return document stats (size, tokens, headings) without content
70678
70950
  toc: external_exports.boolean().optional(),
70679
70951
  // Return table of contents only
70680
- section: external_exports.string().optional()
70952
+ section: external_exports.string().optional(),
70681
70953
  // Return specific section by heading title or number
70954
+ smart: external_exports.boolean().optional()
70955
+ // Smart mode: auto-return full content if small, or stats+TOC if large
70682
70956
  });
70683
70957
  var createDocSchema = external_exports.object({
70684
70958
  title: external_exports.string(),
@@ -70717,7 +70991,7 @@ var docTools = [
70717
70991
  },
70718
70992
  {
70719
70993
  name: "get_doc",
70720
- description: "Get a documentation file by path. Use 'info: true' first to check size, then 'toc: true' for table of contents, then 'section' to read specific parts.",
70994
+ description: "Get a documentation file by path. Use 'smart: true' for auto-optimized reading (recommended for AI), or 'info/toc/section' for manual control.",
70721
70995
  inputSchema: {
70722
70996
  type: "object",
70723
70997
  properties: {
@@ -70725,6 +70999,10 @@ var docTools = [
70725
70999
  type: "string",
70726
71000
  description: "Document path (e.g., 'readme', 'guides/setup', 'conventions/naming.md')"
70727
71001
  },
71002
+ smart: {
71003
+ type: "boolean",
71004
+ description: "Smart mode (recommended): auto-return full content if small (\u22642000 tokens), or stats+TOC if large. Use this by default."
71005
+ },
70728
71006
  info: {
70729
71007
  type: "boolean",
70730
71008
  description: "Return document stats (size, tokens, headings) without content. Use this first to decide how to read."
@@ -70810,7 +71088,7 @@ var docTools = [
70810
71088
  }
70811
71089
  ];
70812
71090
  async function ensureDocsDir2() {
70813
- if (!existsSync16(DOCS_DIR2)) {
71091
+ if (!existsSync17(DOCS_DIR2)) {
70814
71092
  await mkdir9(DOCS_DIR2, { recursive: true });
70815
71093
  }
70816
71094
  }
@@ -70819,13 +71097,13 @@ function titleToFilename2(title) {
70819
71097
  }
70820
71098
  async function getAllMdFiles2(dir, basePath = "") {
70821
71099
  const files = [];
70822
- if (!existsSync16(dir)) {
71100
+ if (!existsSync17(dir)) {
70823
71101
  return files;
70824
71102
  }
70825
71103
  const entries = await readdir6(dir, { withFileTypes: true });
70826
71104
  for (const entry of entries) {
70827
- const fullPath = join20(dir, entry.name);
70828
- const relativePath = normalizePath(basePath ? join20(basePath, entry.name) : entry.name);
71105
+ const fullPath = join21(dir, entry.name);
71106
+ const relativePath = normalizePath(basePath ? join21(basePath, entry.name) : entry.name);
70829
71107
  if (entry.isDirectory()) {
70830
71108
  const subFiles = await getAllMdFiles2(fullPath, relativePath);
70831
71109
  files.push(...subFiles);
@@ -70838,13 +71116,13 @@ async function getAllMdFiles2(dir, basePath = "") {
70838
71116
  async function resolveDocPath2(name) {
70839
71117
  await ensureDocsDir2();
70840
71118
  let filename = name.endsWith(".md") ? name : `${name}.md`;
70841
- let filepath = join20(DOCS_DIR2, filename);
70842
- if (existsSync16(filepath)) {
71119
+ let filepath = join21(DOCS_DIR2, filename);
71120
+ if (existsSync17(filepath)) {
70843
71121
  return { filepath, filename };
70844
71122
  }
70845
71123
  filename = `${titleToFilename2(name)}.md`;
70846
- filepath = join20(DOCS_DIR2, filename);
70847
- if (existsSync16(filepath)) {
71124
+ filepath = join21(DOCS_DIR2, filename);
71125
+ if (existsSync17(filepath)) {
70848
71126
  return { filepath, filename };
70849
71127
  }
70850
71128
  const allFiles = await getAllMdFiles2(DOCS_DIR2);
@@ -70856,7 +71134,7 @@ async function resolveDocPath2(name) {
70856
71134
  });
70857
71135
  if (matchingFile) {
70858
71136
  return {
70859
- filepath: join20(DOCS_DIR2, matchingFile),
71137
+ filepath: join21(DOCS_DIR2, matchingFile),
70860
71138
  filename: matchingFile
70861
71139
  };
70862
71140
  }
@@ -70875,9 +71153,10 @@ async function handleListDocs(args2) {
70875
71153
  }
70876
71154
  const docs = [];
70877
71155
  for (const file3 of mdFiles) {
70878
- const content = await readFile14(join20(DOCS_DIR2, file3), "utf-8");
70879
- const { data } = (0, import_gray_matter8.default)(content);
71156
+ const fileContent = await readFile14(join21(DOCS_DIR2, file3), "utf-8");
71157
+ const { data, content } = (0, import_gray_matter8.default)(fileContent);
70880
71158
  const metadata = data;
71159
+ const stats = calculateDocStats(content);
70881
71160
  if (input.tag && !metadata.tags?.includes(input.tag)) {
70882
71161
  continue;
70883
71162
  }
@@ -70886,6 +71165,7 @@ async function handleListDocs(args2) {
70886
71165
  title: metadata.title || file3.replace(/\.md$/, ""),
70887
71166
  description: metadata.description,
70888
71167
  tags: metadata.tags,
71168
+ tokens: stats.estimatedTokens,
70889
71169
  updatedAt: metadata.updatedAt
70890
71170
  });
70891
71171
  }
@@ -70903,6 +71183,33 @@ async function handleGetDoc(args2) {
70903
71183
  const fileContent = await readFile14(resolved.filepath, "utf-8");
70904
71184
  const { data, content } = (0, import_gray_matter8.default)(fileContent);
70905
71185
  const metadata = data;
71186
+ if (input.smart) {
71187
+ const stats = calculateDocStats(content);
71188
+ const SMART_THRESHOLD = 2e3;
71189
+ if (stats.estimatedTokens <= SMART_THRESHOLD) {
71190
+ } else {
71191
+ const toc = extractToc(content);
71192
+ return successResponse({
71193
+ doc: {
71194
+ path: resolved.filename.replace(/\.md$/, ""),
71195
+ title: metadata.title,
71196
+ smart: true,
71197
+ isLarge: true,
71198
+ stats: {
71199
+ chars: stats.chars,
71200
+ estimatedTokens: stats.estimatedTokens,
71201
+ headingCount: stats.headingCount
71202
+ },
71203
+ toc: toc.map((entry, index) => ({
71204
+ index: index + 1,
71205
+ level: entry.level,
71206
+ title: entry.title
71207
+ })),
71208
+ hint: "Document is large. Use 'section' parameter with a number (e.g., section: '1') to read specific content."
71209
+ }
71210
+ });
71211
+ }
71212
+ }
70906
71213
  if (input.info) {
70907
71214
  const stats = calculateDocStats(content);
70908
71215
  let recommendation;
@@ -70954,7 +71261,8 @@ async function handleGetDoc(args2) {
70954
71261
  });
70955
71262
  }
70956
71263
  if (input.section) {
70957
- const sectionContent = extractSection(content, input.section);
71264
+ const sectionIndex = /^\d+$/.test(input.section) ? Number.parseInt(input.section, 10) : null;
71265
+ const sectionContent = sectionIndex !== null ? extractSectionByIndex(content, sectionIndex) : extractSection(content, input.section);
70958
71266
  if (!sectionContent) {
70959
71267
  return errorResponse(`Section not found: ${input.section}. Use 'toc: true' to see available sections.`);
70960
71268
  }
@@ -70987,14 +71295,14 @@ async function handleCreateDoc(args2) {
70987
71295
  let relativePath = filename;
70988
71296
  if (input.folder) {
70989
71297
  const folderPath = input.folder.replace(/^\/|\/$/g, "");
70990
- targetDir = join20(DOCS_DIR2, folderPath);
70991
- relativePath = join20(folderPath, filename);
70992
- if (!existsSync16(targetDir)) {
71298
+ targetDir = join21(DOCS_DIR2, folderPath);
71299
+ relativePath = join21(folderPath, filename);
71300
+ if (!existsSync17(targetDir)) {
70993
71301
  await mkdir9(targetDir, { recursive: true });
70994
71302
  }
70995
71303
  }
70996
- const filepath = join20(targetDir, filename);
70997
- if (existsSync16(filepath)) {
71304
+ const filepath = join21(targetDir, filename);
71305
+ if (existsSync17(filepath)) {
70998
71306
  return errorResponse(`Document already exists: ${relativePath}`);
70999
71307
  }
71000
71308
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -71039,7 +71347,8 @@ async function handleUpdateDoc(args2) {
71039
71347
  let updatedContent = content;
71040
71348
  let sectionUpdated;
71041
71349
  if (input.section && input.content) {
71042
- const result = replaceSection(content, input.section, input.content);
71350
+ const sectionIndex = /^\d+$/.test(input.section) ? Number.parseInt(input.section, 10) : null;
71351
+ const result = sectionIndex !== null ? replaceSectionByIndex(content, sectionIndex, input.content) : replaceSection(content, input.section, input.content);
71043
71352
  if (!result) {
71044
71353
  return errorResponse(
71045
71354
  `Section not found: ${input.section}. Use 'toc: true' with get_doc to see available sections.`
@@ -71077,7 +71386,7 @@ async function handleSearchDocs(args2) {
71077
71386
  const query = input.query.toLowerCase();
71078
71387
  const results = [];
71079
71388
  for (const file3 of mdFiles) {
71080
- const fileContent = await readFile14(join20(DOCS_DIR2, file3), "utf-8");
71389
+ const fileContent = await readFile14(join21(DOCS_DIR2, file3), "utf-8");
71081
71390
  const { data, content } = (0, import_gray_matter8.default)(fileContent);
71082
71391
  const metadata = data;
71083
71392
  if (input.tag && !metadata.tags?.includes(input.tag)) {
@@ -71225,7 +71534,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
71225
71534
  });
71226
71535
  server.setRequestHandler(ListResourcesRequestSchema, async () => {
71227
71536
  const tasks = await fileStore.getAllTasks();
71228
- const docsDir = join21(process.cwd(), ".knowns", "docs");
71537
+ const docsDir = join22(process.cwd(), ".knowns", "docs");
71229
71538
  const taskResources = tasks.map((task) => ({
71230
71539
  uri: `knowns://task/${task.id}`,
71231
71540
  name: task.title,
@@ -71233,14 +71542,14 @@ server.setRequestHandler(ListResourcesRequestSchema, async () => {
71233
71542
  description: `Task #${task.id}: ${task.title}`
71234
71543
  }));
71235
71544
  const docResources = [];
71236
- if (existsSync17(docsDir)) {
71545
+ if (existsSync18(docsDir)) {
71237
71546
  const { readdir: readdir7 } = await import("node:fs/promises");
71238
71547
  async function getAllMdFiles3(dir, basePath = "") {
71239
71548
  const files = [];
71240
71549
  const entries = await readdir7(dir, { withFileTypes: true });
71241
71550
  for (const entry of entries) {
71242
- const fullPath = join21(dir, entry.name);
71243
- const relativePath = normalizePath(basePath ? join21(basePath, entry.name) : entry.name);
71551
+ const fullPath = join22(dir, entry.name);
71552
+ const relativePath = normalizePath(basePath ? join22(basePath, entry.name) : entry.name);
71244
71553
  if (entry.isDirectory()) {
71245
71554
  const subFiles = await getAllMdFiles3(fullPath, relativePath);
71246
71555
  files.push(...subFiles);
@@ -71252,7 +71561,7 @@ server.setRequestHandler(ListResourcesRequestSchema, async () => {
71252
71561
  }
71253
71562
  const mdFiles = await getAllMdFiles3(docsDir);
71254
71563
  for (const file3 of mdFiles) {
71255
- const filepath = join21(docsDir, file3);
71564
+ const filepath = join22(docsDir, file3);
71256
71565
  const content = await readFile15(filepath, "utf-8");
71257
71566
  const { data } = (0, import_gray_matter9.default)(content);
71258
71567
  docResources.push({
@@ -71289,9 +71598,9 @@ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
71289
71598
  const docMatch = uri.match(/^knowns:\/\/doc\/(.+)$/);
71290
71599
  if (docMatch) {
71291
71600
  const docPath = docMatch[1];
71292
- const docsDir = join21(process.cwd(), ".knowns", "docs");
71293
- const filepath = join21(docsDir, `${docPath}.md`);
71294
- if (!existsSync17(filepath)) {
71601
+ const docsDir = join22(process.cwd(), ".knowns", "docs");
71602
+ const filepath = join22(docsDir, `${docPath}.md`);
71603
+ if (!existsSync18(filepath)) {
71295
71604
  throw new Error(`Documentation ${docPath} not found`);
71296
71605
  }
71297
71606
  const content = await readFile15(filepath, "utf-8");
@@ -71373,15 +71682,15 @@ async function setupClaudeCode() {
71373
71682
  return false;
71374
71683
  }
71375
71684
  function createProjectMcpJson(projectRoot) {
71376
- const mcpJsonPath = join22(projectRoot, ".mcp.json");
71685
+ const mcpJsonPath = join23(projectRoot, ".mcp.json");
71377
71686
  const mcpConfig = {
71378
71687
  mcpServers: {
71379
71688
  knowns: getMcpConfig()
71380
71689
  }
71381
71690
  };
71382
- if (existsSync18(mcpJsonPath)) {
71691
+ if (existsSync19(mcpJsonPath)) {
71383
71692
  try {
71384
- const existing = JSON.parse(readFileSync2(mcpJsonPath, "utf-8"));
71693
+ const existing = JSON.parse(readFileSync3(mcpJsonPath, "utf-8"));
71385
71694
  if (existing?.mcpServers?.knowns) {
71386
71695
  console.log(source_default.gray(" .mcp.json already has knowns configuration"));
71387
71696
  return true;
@@ -71390,14 +71699,14 @@ function createProjectMcpJson(projectRoot) {
71390
71699
  ...existing.mcpServers,
71391
71700
  ...mcpConfig.mcpServers
71392
71701
  };
71393
- writeFileSync(mcpJsonPath, JSON.stringify(existing, null, " "), "utf-8");
71702
+ writeFileSync2(mcpJsonPath, JSON.stringify(existing, null, " "), "utf-8");
71394
71703
  console.log(source_default.green("\u2713 Added knowns to existing .mcp.json"));
71395
71704
  } catch {
71396
- writeFileSync(mcpJsonPath, JSON.stringify(mcpConfig, null, " "), "utf-8");
71705
+ writeFileSync2(mcpJsonPath, JSON.stringify(mcpConfig, null, " "), "utf-8");
71397
71706
  console.log(source_default.green("\u2713 Created .mcp.json (replaced invalid file)"));
71398
71707
  }
71399
71708
  } else {
71400
- writeFileSync(mcpJsonPath, JSON.stringify(mcpConfig, null, " "), "utf-8");
71709
+ writeFileSync2(mcpJsonPath, JSON.stringify(mcpConfig, null, " "), "utf-8");
71401
71710
  console.log(source_default.green("\u2713 Created .mcp.json for Claude Code project-level auto-discovery"));
71402
71711
  }
71403
71712
  return true;
@@ -71479,10 +71788,10 @@ function showConfigInfo() {
71479
71788
  }
71480
71789
 
71481
71790
  // src/utils/update-notifier.ts
71482
- import { existsSync as existsSync19, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
71791
+ import { existsSync as existsSync20, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "node:fs";
71483
71792
  import { mkdir as mkdir10 } from "node:fs/promises";
71484
71793
  import { homedir } from "node:os";
71485
- import { dirname as dirname4, join as join23 } from "node:path";
71794
+ import { dirname as dirname4, join as join24 } from "node:path";
71486
71795
  var DEFAULT_TTL_MS = 60 * 60 * 1e3;
71487
71796
  var DEFAULT_TIMEOUT_MS = 2e3;
71488
71797
  function detectPackageManager(cwd) {
@@ -71495,10 +71804,10 @@ function detectPackageManager(cwd) {
71495
71804
  if (ua.startsWith("yarn/")) return "yarn";
71496
71805
  if (ua.startsWith("bun/")) return "bun";
71497
71806
  if (ua.startsWith("npm/")) return "npm";
71498
- if (existsSync19(join23(cwd, "pnpm-lock.yaml"))) return "pnpm";
71499
- if (existsSync19(join23(cwd, "yarn.lock"))) return "yarn";
71500
- if (existsSync19(join23(cwd, "bun.lock"))) return "bun";
71501
- if (existsSync19(join23(cwd, "package-lock.json"))) return "npm";
71807
+ if (existsSync20(join24(cwd, "pnpm-lock.yaml"))) return "pnpm";
71808
+ if (existsSync20(join24(cwd, "yarn.lock"))) return "yarn";
71809
+ if (existsSync20(join24(cwd, "bun.lock"))) return "bun";
71810
+ if (existsSync20(join24(cwd, "package-lock.json"))) return "npm";
71502
71811
  return "npm";
71503
71812
  }
71504
71813
  function compareVersions(a, b) {
@@ -71522,11 +71831,11 @@ function shouldSkip(args2, force) {
71522
71831
  }
71523
71832
  function getGlobalCachePath(explicit) {
71524
71833
  if (explicit) return explicit;
71525
- return join23(homedir(), ".knowns", "cli-cache.json");
71834
+ return join24(homedir(), ".knowns", "cli-cache.json");
71526
71835
  }
71527
71836
  function readCache(cachePath) {
71528
71837
  try {
71529
- const raw = readFileSync3(cachePath, "utf-8");
71838
+ const raw = readFileSync4(cachePath, "utf-8");
71530
71839
  const data = JSON.parse(raw);
71531
71840
  if (typeof data.lastChecked === "number" && typeof data.latestVersion === "string") {
71532
71841
  return data;
@@ -71538,10 +71847,10 @@ function readCache(cachePath) {
71538
71847
  }
71539
71848
  async function writeCache(cachePath, data) {
71540
71849
  const dir = dirname4(cachePath);
71541
- if (dir && !existsSync19(dir)) {
71850
+ if (dir && !existsSync20(dir)) {
71542
71851
  await mkdir10(dir, { recursive: true });
71543
71852
  }
71544
- writeFileSync2(cachePath, JSON.stringify(data, null, 2), "utf-8");
71853
+ writeFileSync3(cachePath, JSON.stringify(data, null, 2), "utf-8");
71545
71854
  }
71546
71855
  async function fetchLatestVersion(packageName) {
71547
71856
  try {
@@ -71604,7 +71913,7 @@ async function notifyCliUpdate(options2) {
71604
71913
  // package.json
71605
71914
  var package_default = {
71606
71915
  name: "knowns",
71607
- version: "0.8.8",
71916
+ version: "0.9.0",
71608
71917
  description: "AI-native task and documentation management for dev teams",
71609
71918
  module: "index.ts",
71610
71919
  type: "module",
@@ -71760,6 +72069,7 @@ program2.addCommand(searchCommand);
71760
72069
  program2.addCommand(timeCommand);
71761
72070
  program2.addCommand(docCommand);
71762
72071
  program2.addCommand(configCommand);
72072
+ program2.addCommand(syncCommand);
71763
72073
  program2.addCommand(agentsCommand);
71764
72074
  program2.addCommand(mcpCommand);
71765
72075
  var args = process.argv.slice(2);