claude-code-workflow 6.3.37 → 6.3.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/.claude/commands/workflow/lite-execute.md +2 -0
  2. package/.codex/agents/action-planning-agent.md +885 -0
  3. package/.codex/agents/ccw-loop-b-complete.md +227 -0
  4. package/.codex/agents/ccw-loop-b-debug.md +172 -0
  5. package/.codex/agents/ccw-loop-b-develop.md +147 -0
  6. package/.codex/agents/ccw-loop-b-init.md +82 -0
  7. package/.codex/agents/ccw-loop-b-validate.md +204 -0
  8. package/.codex/agents/ccw-loop-executor.md +260 -0
  9. package/.codex/agents/cli-discuss-agent.md +391 -0
  10. package/.codex/agents/cli-execution-agent.md +333 -0
  11. package/.codex/agents/cli-explore-agent.md +186 -0
  12. package/.codex/agents/cli-lite-planning-agent.md +736 -0
  13. package/.codex/agents/cli-planning-agent.md +562 -0
  14. package/.codex/agents/code-developer.md +408 -0
  15. package/.codex/agents/conceptual-planning-agent.md +321 -0
  16. package/.codex/agents/context-search-agent.md +585 -0
  17. package/.codex/agents/debug-explore-agent.md +436 -0
  18. package/.codex/agents/doc-generator.md +334 -0
  19. package/.codex/agents/issue-plan-agent.md +417 -0
  20. package/.codex/agents/issue-queue-agent.md +311 -0
  21. package/.codex/agents/memory-bridge.md +96 -0
  22. package/.codex/agents/test-context-search-agent.md +402 -0
  23. package/.codex/agents/test-fix-agent.md +359 -0
  24. package/.codex/agents/ui-design-agent.md +595 -0
  25. package/.codex/agents/universal-executor.md +135 -0
  26. package/.codex/prompts/clean.md +409 -0
  27. package/.codex/prompts/issue-discover-by-prompt.md +364 -0
  28. package/.codex/prompts/issue-discover.md +261 -0
  29. package/.codex/prompts/issue-execute.md +10 -0
  30. package/.codex/prompts/issue-new.md +285 -0
  31. package/.codex/prompts/issue-plan.md +161 -63
  32. package/.codex/prompts/issue-queue.md +298 -288
  33. package/.codex/prompts/lite-execute.md +627 -133
  34. package/.codex/prompts/lite-fix.md +670 -0
  35. package/.codex/prompts/lite-plan-a.md +337 -0
  36. package/.codex/prompts/lite-plan-b.md +485 -0
  37. package/.codex/prompts/{lite-plan.md → lite-plan-c.md} +601 -469
  38. package/.codex/skills/ccw-loop/README.md +171 -0
  39. package/.codex/skills/ccw-loop/SKILL.md +349 -0
  40. package/.codex/skills/ccw-loop/phases/actions/action-complete.md +269 -0
  41. package/.codex/skills/ccw-loop/phases/actions/action-debug.md +286 -0
  42. package/.codex/skills/ccw-loop/phases/actions/action-develop.md +183 -0
  43. package/.codex/skills/ccw-loop/phases/actions/action-init.md +164 -0
  44. package/.codex/skills/ccw-loop/phases/actions/action-menu.md +205 -0
  45. package/.codex/skills/ccw-loop/phases/actions/action-validate.md +250 -0
  46. package/.codex/skills/ccw-loop/phases/orchestrator.md +416 -0
  47. package/.codex/skills/ccw-loop/phases/state-schema.md +388 -0
  48. package/.codex/skills/ccw-loop/specs/action-catalog.md +182 -0
  49. package/.codex/skills/ccw-loop-b/README.md +301 -0
  50. package/.codex/skills/ccw-loop-b/SKILL.md +322 -0
  51. package/.codex/skills/ccw-loop-b/phases/orchestrator.md +257 -0
  52. package/.codex/skills/ccw-loop-b/phases/state-schema.md +181 -0
  53. package/.codex/skills/ccw-loop-b/specs/action-catalog.md +383 -0
  54. package/.codex/skills/parallel-dev-cycle/README.md +382 -0
  55. package/.codex/skills/parallel-dev-cycle/SKILL.md +512 -0
  56. package/.codex/skills/parallel-dev-cycle/phases/agents/code-developer.md +242 -0
  57. package/.codex/skills/parallel-dev-cycle/phases/agents/exploration-planner.md +285 -0
  58. package/.codex/skills/parallel-dev-cycle/phases/agents/requirements-analyst.md +285 -0
  59. package/.codex/skills/parallel-dev-cycle/phases/agents/validation-archivist.md +381 -0
  60. package/.codex/skills/parallel-dev-cycle/phases/orchestrator.md +696 -0
  61. package/.codex/skills/parallel-dev-cycle/phases/state-schema.md +436 -0
  62. package/.codex/skills/parallel-dev-cycle/specs/communication-optimization.md +423 -0
  63. package/.codex/skills/parallel-dev-cycle/specs/coordination-protocol.md +391 -0
  64. package/.codex/skills/parallel-dev-cycle/specs/versioning-strategy.md +330 -0
  65. package/ccw/dist/cli.d.ts.map +1 -1
  66. package/ccw/dist/cli.js +4 -0
  67. package/ccw/dist/cli.js.map +1 -1
  68. package/ccw/dist/commands/install.d.ts.map +1 -1
  69. package/ccw/dist/commands/install.js +39 -8
  70. package/ccw/dist/commands/install.js.map +1 -1
  71. package/ccw/dist/commands/issue.d.ts +3 -0
  72. package/ccw/dist/commands/issue.d.ts.map +1 -1
  73. package/ccw/dist/commands/issue.js +107 -0
  74. package/ccw/dist/commands/issue.js.map +1 -1
  75. package/ccw/dist/commands/upgrade.js +1 -1
  76. package/ccw/dist/commands/upgrade.js.map +1 -1
  77. package/ccw/dist/config/litellm-api-config-manager.d.ts.map +1 -1
  78. package/ccw/dist/config/litellm-api-config-manager.js +3 -2
  79. package/ccw/dist/config/litellm-api-config-manager.js.map +1 -1
  80. package/ccw/dist/core/memory-embedder-bridge.d.ts.map +1 -1
  81. package/ccw/dist/core/memory-embedder-bridge.js +2 -5
  82. package/ccw/dist/core/memory-embedder-bridge.js.map +1 -1
  83. package/ccw/dist/core/routes/cli-routes.js.map +1 -1
  84. package/ccw/dist/core/routes/codexlens/config-handlers.d.ts.map +1 -1
  85. package/ccw/dist/core/routes/codexlens/config-handlers.js +7 -6
  86. package/ccw/dist/core/routes/codexlens/config-handlers.js.map +1 -1
  87. package/ccw/dist/core/routes/codexlens/semantic-handlers.d.ts.map +1 -1
  88. package/ccw/dist/core/routes/codexlens/semantic-handlers.js +2 -2
  89. package/ccw/dist/core/routes/codexlens/semantic-handlers.js.map +1 -1
  90. package/ccw/dist/core/routes/graph-routes.d.ts.map +1 -1
  91. package/ccw/dist/core/routes/graph-routes.js +17 -2
  92. package/ccw/dist/core/routes/graph-routes.js.map +1 -1
  93. package/ccw/dist/core/routes/issue-routes.d.ts.map +1 -1
  94. package/ccw/dist/core/routes/issue-routes.js +280 -33
  95. package/ccw/dist/core/routes/issue-routes.js.map +1 -1
  96. package/ccw/dist/core/routes/loop-v2-routes.d.ts +9 -0
  97. package/ccw/dist/core/routes/loop-v2-routes.d.ts.map +1 -1
  98. package/ccw/dist/core/routes/loop-v2-routes.js +56 -4
  99. package/ccw/dist/core/routes/loop-v2-routes.js.map +1 -1
  100. package/ccw/dist/core/routes/system-routes.d.ts.map +1 -1
  101. package/ccw/dist/core/routes/system-routes.js +3 -2
  102. package/ccw/dist/core/routes/system-routes.js.map +1 -1
  103. package/ccw/dist/core/server.d.ts.map +1 -1
  104. package/ccw/dist/core/server.js +5 -3
  105. package/ccw/dist/core/server.js.map +1 -1
  106. package/ccw/dist/tools/claude-cli-tools.d.ts.map +1 -1
  107. package/ccw/dist/tools/claude-cli-tools.js +4 -3
  108. package/ccw/dist/tools/claude-cli-tools.js.map +1 -1
  109. package/ccw/dist/tools/cli-config-manager.d.ts +1 -0
  110. package/ccw/dist/tools/cli-config-manager.d.ts.map +1 -1
  111. package/ccw/dist/tools/cli-config-manager.js +2 -1
  112. package/ccw/dist/tools/cli-config-manager.js.map +1 -1
  113. package/ccw/dist/tools/codex-lens-lsp.d.ts.map +1 -1
  114. package/ccw/dist/tools/codex-lens-lsp.js +2 -5
  115. package/ccw/dist/tools/codex-lens-lsp.js.map +1 -1
  116. package/ccw/dist/tools/codex-lens.d.ts.map +1 -1
  117. package/ccw/dist/tools/codex-lens.js +22 -32
  118. package/ccw/dist/tools/codex-lens.js.map +1 -1
  119. package/ccw/dist/tools/litellm-client.d.ts +6 -0
  120. package/ccw/dist/tools/litellm-client.d.ts.map +1 -1
  121. package/ccw/dist/tools/litellm-client.js +15 -2
  122. package/ccw/dist/tools/litellm-client.js.map +1 -1
  123. package/ccw/dist/tools/loop-task-manager.d.ts +13 -2
  124. package/ccw/dist/tools/loop-task-manager.d.ts.map +1 -1
  125. package/ccw/dist/tools/loop-task-manager.js.map +1 -1
  126. package/ccw/dist/tools/native-session-discovery.d.ts.map +1 -1
  127. package/ccw/dist/tools/native-session-discovery.js +35 -7
  128. package/ccw/dist/tools/native-session-discovery.js.map +1 -1
  129. package/ccw/dist/utils/codexlens-path.d.ts +36 -0
  130. package/ccw/dist/utils/codexlens-path.d.ts.map +1 -0
  131. package/ccw/dist/utils/codexlens-path.js +56 -0
  132. package/ccw/dist/utils/codexlens-path.js.map +1 -0
  133. package/ccw/dist/utils/uv-manager.d.ts.map +1 -1
  134. package/ccw/dist/utils/uv-manager.js +3 -2
  135. package/ccw/dist/utils/uv-manager.js.map +1 -1
  136. package/ccw/src/cli.ts +4 -0
  137. package/ccw/src/commands/install.ts +51 -8
  138. package/ccw/src/commands/issue.ts +119 -0
  139. package/ccw/src/commands/upgrade.ts +1 -1
  140. package/ccw/src/config/litellm-api-config-manager.ts +3 -2
  141. package/ccw/src/core/memory-embedder-bridge.ts +2 -6
  142. package/ccw/src/core/routes/cli-routes.ts +1 -1
  143. package/ccw/src/core/routes/codexlens/config-handlers.ts +7 -6
  144. package/ccw/src/core/routes/codexlens/semantic-handlers.ts +2 -2
  145. package/ccw/src/core/routes/graph-routes.ts +18 -2
  146. package/ccw/src/core/routes/issue-routes.ts +308 -33
  147. package/ccw/src/core/routes/loop-v2-routes.ts +64 -6
  148. package/ccw/src/core/routes/system-routes.ts +3 -2
  149. package/ccw/src/core/server.ts +6 -3
  150. package/ccw/src/templates/dashboard-css/02-session.css +2 -0
  151. package/ccw/src/templates/dashboard-css/04-lite-tasks.css +103 -1
  152. package/ccw/src/templates/dashboard-css/32-issue-manager.css +32 -0
  153. package/ccw/src/templates/dashboard-js/components/cli-history.js +48 -48
  154. package/ccw/src/templates/dashboard-js/components/navigation.js +6 -0
  155. package/ccw/src/templates/dashboard-js/components/notifications.js +6 -0
  156. package/ccw/src/templates/dashboard-js/components/version-check.js +38 -0
  157. package/ccw/src/templates/dashboard-js/i18n.js +126 -0
  158. package/ccw/src/templates/dashboard-js/state.js +2 -0
  159. package/ccw/src/templates/dashboard-js/views/cli-manager.js +1 -1
  160. package/ccw/src/templates/dashboard-js/views/issue-manager.js +183 -1
  161. package/ccw/src/templates/dashboard-js/views/lite-tasks.js +55 -11
  162. package/ccw/src/templates/dashboard-js/views/loop-monitor.js +112 -11
  163. package/ccw/src/templates/dashboard.html +48 -2
  164. package/ccw/src/tools/claude-cli-tools.ts +4 -3
  165. package/ccw/src/tools/cli-config-manager.ts +3 -1
  166. package/ccw/src/tools/codex-lens-lsp.ts +2 -5
  167. package/ccw/src/tools/codex-lens.ts +27 -38
  168. package/ccw/src/tools/litellm-client.ts +16 -2
  169. package/ccw/src/tools/loop-task-manager.ts +13 -2
  170. package/ccw/src/tools/native-session-discovery.ts +38 -7
  171. package/ccw/src/utils/codexlens-path.ts +60 -0
  172. package/ccw/src/utils/uv-manager.ts +3 -2
  173. package/package.json +1 -1
@@ -0,0 +1,135 @@
1
+ ---
2
+ name: universal-executor
3
+ description: |
4
+ Versatile execution agent for implementing any task efficiently. Adapts to any domain while maintaining quality standards and systematic execution. Can handle analysis, implementation, documentation, research, and complex multi-step workflows.
5
+
6
+ Examples:
7
+ - Context: User provides task with sufficient context
8
+ user: "Analyze market trends and create presentation following these guidelines: [context]"
9
+ assistant: "I'll analyze the market trends and create the presentation using the provided guidelines"
10
+ commentary: Execute task directly with user-provided context
11
+
12
+ - Context: User provides insufficient context
13
+ user: "Organize project documentation"
14
+ assistant: "I need to understand the current documentation structure first"
15
+ commentary: Gather context about existing documentation, then execute
16
+ color: green
17
+ ---
18
+
19
+ You are a versatile execution specialist focused on completing high-quality tasks efficiently across any domain. You receive tasks with context and execute them systematically using proven methodologies.
20
+
21
+ ## Core Execution Philosophy
22
+
23
+ - **Incremental progress** - Break down complex tasks into manageable steps
24
+ - **Context-driven** - Use provided context and existing patterns
25
+ - **Quality over speed** - Deliver reliable, well-executed results
26
+ - **Adaptability** - Adjust approach based on task domain and requirements
27
+
28
+ ## Execution Process
29
+
30
+ ### 1. Context Assessment
31
+ **Input Sources**:
32
+ - User-provided task description and context
33
+ - **MCP Tools Selection**: Choose appropriate tools based on task type (Code Index for codebase, Exa for research)
34
+ - Existing documentation and examples
35
+ - Project CLAUDE.md standards
36
+ - Domain-specific requirements
37
+
38
+ **Context Evaluation**:
39
+ ```
40
+ IF context sufficient for execution:
41
+ → Proceed with task execution
42
+ ELIF context insufficient OR task has flow control marker:
43
+ → Check for [FLOW_CONTROL] marker:
44
+ - Execute flow_control.pre_analysis steps sequentially for context gathering
45
+ - Use four flexible context acquisition methods:
46
+ * Document references (cat commands)
47
+ * Search commands (grep/rg/find)
48
+ * CLI analysis (gemini/codex)
49
+ * Free exploration (Read/Grep/Search tools)
50
+ - Pass context between steps via [variable_name] references
51
+ → Extract patterns and conventions from accumulated context
52
+ → Proceed with execution
53
+ ```
54
+
55
+ ### 2. Execution Standards
56
+
57
+ **Systematic Approach**:
58
+ - Break complex tasks into clear, manageable steps
59
+ - Validate assumptions and requirements before proceeding
60
+ - Document decisions and reasoning throughout the process
61
+ - Ensure each step builds logically on previous work
62
+
63
+ **Quality Standards**:
64
+ - Single responsibility per task/subtask
65
+ - Clear, descriptive naming and organization
66
+ - Explicit handling of edge cases and errors
67
+ - No unnecessary complexity
68
+ - Follow established patterns and conventions
69
+
70
+ **Verification Guidelines**:
71
+ - Before referencing existing resources, verify their existence and relevance
72
+ - Test intermediate results before proceeding to next steps
73
+ - Ensure outputs meet specified requirements
74
+ - Validate final deliverables against original task goals
75
+
76
+ ### 3. Quality Gates
77
+ **Before Task Completion**:
78
+ - All deliverables meet specified requirements
79
+ - Work functions/operates as intended
80
+ - Follows discovered patterns and conventions
81
+ - Clear organization and documentation
82
+ - Proper handling of edge cases
83
+
84
+ ### 4. Task Completion
85
+
86
+ **Upon completing any task:**
87
+
88
+ 1. **Verify Implementation**:
89
+ - Deliverables meet all requirements
90
+ - Work functions as specified
91
+ - Quality standards maintained
92
+
93
+ ### 5. Problem-Solving
94
+
95
+ **When facing challenges** (max 3 attempts):
96
+ 1. Document specific obstacles and constraints
97
+ 2. Try 2-3 alternative approaches
98
+ 3. Consider simpler or alternative solutions
99
+ 4. After 3 attempts, escalate for consultation
100
+
101
+ ## Quality Checklist
102
+
103
+ Before completing any task, verify:
104
+ - [ ] **Resource verification complete** - All referenced resources/dependencies exist
105
+ - [ ] Deliverables meet all specified requirements
106
+ - [ ] Work functions/operates as intended
107
+ - [ ] Follows established patterns and conventions
108
+ - [ ] Clear organization and documentation
109
+ - [ ] No unnecessary complexity
110
+ - [ ] Proper handling of edge cases
111
+ - [ ] TODO list updated
112
+ - [ ] Comprehensive summary document generated with all deliverables listed
113
+
114
+ ## Key Reminders
115
+
116
+ **NEVER:**
117
+ - Reference resources without verifying existence first
118
+ - Create deliverables that don't meet requirements
119
+ - Add unnecessary complexity
120
+ - Make assumptions - verify with existing materials
121
+ - Skip quality verification steps
122
+
123
+ **Bash Tool**:
124
+ - Use `run_in_background=false` for all Bash/CLI calls to ensure foreground execution
125
+
126
+ **ALWAYS:**
127
+ - **Search Tool Priority**: ACE (`mcp__ace-tool__search_context`) → CCW (`mcp__ccw-tools__smart_search`) / Built-in (`Grep`, `Glob`, `Read`)
128
+ - Verify resource/dependency existence before referencing
129
+ - Execute tasks systematically and incrementally
130
+ - Test and validate work thoroughly
131
+ - Follow established patterns and conventions
132
+ - Handle edge cases appropriately
133
+ - Keep tasks focused and manageable
134
+ - Generate detailed summary documents with complete deliverable listings
135
+ - Document all key outputs and integration points for dependent tasks
@@ -0,0 +1,409 @@
1
+ ---
2
+ description: Intelligent code cleanup with mainline detection, stale artifact discovery, and safe execution
3
+ argument-hint: [--dry-run] [FOCUS="<area>"]
4
+ ---
5
+
6
+ # Workflow Clean Command
7
+
8
+ ## Overview
9
+
10
+ Evidence-based intelligent cleanup command. Systematically identifies stale artifacts through mainline analysis, discovers drift, and safely removes unused sessions, documents, and dead code.
11
+
12
+ **Core workflow**: Detect Mainline → Discover Drift → Confirm → Stage → Execute
13
+
14
+ ## Target Cleanup
15
+
16
+ **Focus area**: $FOCUS (or entire project if not specified)
17
+ **Mode**: $ARGUMENTS
18
+
19
+ ## Execution Process
20
+
21
+ ```
22
+ Phase 0: Initialization
23
+ ├─ Parse arguments (--dry-run, FOCUS)
24
+ ├─ Setup session folder
25
+ └─ Initialize utility functions
26
+
27
+ Phase 1: Mainline Detection
28
+ ├─ Analyze git history (30 days)
29
+ ├─ Identify core modules (high commit frequency)
30
+ ├─ Map active vs stale branches
31
+ └─ Build mainline profile
32
+
33
+ Phase 2: Drift Discovery (Subagent)
34
+ ├─ spawn_agent with cli-explore-agent role
35
+ ├─ Scan workflow sessions for orphaned artifacts
36
+ ├─ Identify documents drifted from mainline
37
+ ├─ Detect dead code and unused exports
38
+ └─ Generate cleanup manifest
39
+
40
+ Phase 3: Confirmation
41
+ ├─ Validate manifest schema
42
+ ├─ Display cleanup summary by category
43
+ ├─ AskUser: Select categories and risk level
44
+ └─ Dry-run exit if --dry-run
45
+
46
+ Phase 4: Execution
47
+ ├─ Validate paths (security check)
48
+ ├─ Stage deletion (move to .trash)
49
+ ├─ Update manifests
50
+ ├─ Permanent deletion
51
+ └─ Report results
52
+ ```
53
+
54
+ ## Implementation
55
+
56
+ ### Phase 0: Initialization
57
+
58
+ ```javascript
59
+ const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
60
+
61
+ // Parse arguments
62
+ const args = "$ARGUMENTS"
63
+ const isDryRun = args.includes('--dry-run')
64
+ const focusMatch = args.match(/FOCUS="([^"]+)"/)
65
+ const focusArea = focusMatch ? focusMatch[1] : "$FOCUS" !== "$" + "FOCUS" ? "$FOCUS" : null
66
+
67
+ // Session setup
68
+ const dateStr = getUtc8ISOString().substring(0, 10)
69
+ const sessionId = `clean-${dateStr}`
70
+ const sessionFolder = `.workflow/.clean/${sessionId}`
71
+ const trashFolder = `${sessionFolder}/.trash`
72
+ const projectRoot = process.cwd()
73
+
74
+ bash(`mkdir -p ${sessionFolder}`)
75
+ bash(`mkdir -p ${trashFolder}`)
76
+
77
+ // Utility functions
78
+ function fileExists(p) {
79
+ try { return bash(`test -f "${p}" && echo "yes"`).includes('yes') } catch { return false }
80
+ }
81
+
82
+ function dirExists(p) {
83
+ try { return bash(`test -d "${p}" && echo "yes"`).includes('yes') } catch { return false }
84
+ }
85
+
86
+ function validatePath(targetPath) {
87
+ if (targetPath.includes('..')) return { valid: false, reason: 'Path traversal' }
88
+
89
+ const allowed = ['.workflow/', '.claude/rules/tech/', 'src/']
90
+ const dangerous = [/^\//, /^C:\\Windows/i, /node_modules/, /\.git$/]
91
+
92
+ if (!allowed.some(p => targetPath.startsWith(p))) {
93
+ return { valid: false, reason: 'Outside allowed directories' }
94
+ }
95
+ if (dangerous.some(p => p.test(targetPath))) {
96
+ return { valid: false, reason: 'Dangerous pattern' }
97
+ }
98
+ return { valid: true }
99
+ }
100
+ ```
101
+
102
+ ---
103
+
104
+ ### Phase 1: Mainline Detection
105
+
106
+ ```javascript
107
+ // Check git repository
108
+ const isGitRepo = bash('git rev-parse --git-dir 2>/dev/null && echo "yes"').includes('yes')
109
+
110
+ let mainlineProfile = {
111
+ coreModules: [],
112
+ activeFiles: [],
113
+ activeBranches: [],
114
+ staleThreshold: { sessions: 7, branches: 30, documents: 14 },
115
+ isGitRepo,
116
+ timestamp: getUtc8ISOString()
117
+ }
118
+
119
+ if (isGitRepo) {
120
+ // Commit frequency by directory (last 30 days)
121
+ const freq = bash('git log --since="30 days ago" --name-only --pretty=format: | grep -v "^$" | cut -d/ -f1-2 | sort | uniq -c | sort -rn | head -20')
122
+
123
+ // Parse core modules (>5 commits)
124
+ mainlineProfile.coreModules = freq.trim().split('\n')
125
+ .map(l => l.trim().match(/^(\d+)\s+(.+)$/))
126
+ .filter(m => m && parseInt(m[1]) >= 5)
127
+ .map(m => m[2])
128
+
129
+ // Recent branches
130
+ const branches = bash('git for-each-ref --sort=-committerdate refs/heads/ --format="%(refname:short)" | head -10')
131
+ mainlineProfile.activeBranches = branches.trim().split('\n').filter(Boolean)
132
+ }
133
+
134
+ Write(`${sessionFolder}/mainline-profile.json`, JSON.stringify(mainlineProfile, null, 2))
135
+ ```
136
+
137
+ ---
138
+
139
+ ### Phase 2: Drift Discovery
140
+
141
+ ```javascript
142
+ let exploreAgent = null
143
+
144
+ try {
145
+ // Launch cli-explore-agent
146
+ exploreAgent = spawn_agent({
147
+ message: `
148
+ ## TASK ASSIGNMENT
149
+
150
+ ### MANDATORY FIRST STEPS
151
+ 1. Read: ~/.codex/agents/cli-explore-agent.md
152
+ 2. Read: .workflow/project-tech.json (if exists)
153
+
154
+ ## Task Objective
155
+ Discover stale artifacts for cleanup.
156
+
157
+ ## Context
158
+ - Session: ${sessionFolder}
159
+ - Focus: ${focusArea || 'entire project'}
160
+
161
+ ## Discovery Categories
162
+
163
+ ### 1. Stale Workflow Sessions
164
+ Scan: .workflow/active/WFS-*, .workflow/archives/WFS-*, .workflow/.lite-plan/*, .workflow/.debug/DBG-*
165
+ Criteria: No modification >7 days + no related git commits
166
+
167
+ ### 2. Drifted Documents
168
+ Scan: .claude/rules/tech/*, .workflow/.scratchpad/*
169
+ Criteria: >30% broken references to non-existent files
170
+
171
+ ### 3. Dead Code
172
+ Scan: Unused exports, orphan files (not imported anywhere)
173
+ Criteria: No importers in import graph
174
+
175
+ ## Output
176
+ Write to: ${sessionFolder}/cleanup-manifest.json
177
+
178
+ Format:
179
+ {
180
+ "generated_at": "ISO",
181
+ "discoveries": {
182
+ "stale_sessions": [{ "path": "...", "age_days": N, "reason": "...", "risk": "low|medium|high" }],
183
+ "drifted_documents": [{ "path": "...", "drift_percentage": N, "reason": "...", "risk": "..." }],
184
+ "dead_code": [{ "path": "...", "type": "orphan_file", "reason": "...", "risk": "..." }]
185
+ },
186
+ "summary": { "total_items": N, "by_category": {...}, "by_risk": {...} }
187
+ }
188
+ `
189
+ })
190
+
191
+ // Wait with timeout handling
192
+ let result = wait({ ids: [exploreAgent], timeout_ms: 600000 })
193
+
194
+ if (result.timed_out) {
195
+ send_input({ id: exploreAgent, message: 'Complete now and write cleanup-manifest.json.' })
196
+ result = wait({ ids: [exploreAgent], timeout_ms: 300000 })
197
+ if (result.timed_out) throw new Error('Agent timeout')
198
+ }
199
+
200
+ if (!fileExists(`${sessionFolder}/cleanup-manifest.json`)) {
201
+ throw new Error('Manifest not generated')
202
+ }
203
+
204
+ } finally {
205
+ if (exploreAgent) close_agent({ id: exploreAgent })
206
+ }
207
+ ```
208
+
209
+ ---
210
+
211
+ ### Phase 3: Confirmation
212
+
213
+ ```javascript
214
+ // Load and validate manifest
215
+ const manifest = JSON.parse(Read(`${sessionFolder}/cleanup-manifest.json`))
216
+
217
+ // Display summary
218
+ console.log(`
219
+ ## Cleanup Discovery Report
220
+
221
+ | Category | Count | Risk |
222
+ |----------|-------|------|
223
+ | Sessions | ${manifest.summary.by_category.stale_sessions} | ${getRiskSummary('sessions')} |
224
+ | Documents | ${manifest.summary.by_category.drifted_documents} | ${getRiskSummary('documents')} |
225
+ | Dead Code | ${manifest.summary.by_category.dead_code} | ${getRiskSummary('code')} |
226
+
227
+ **Total**: ${manifest.summary.total_items} items
228
+ `)
229
+
230
+ // Dry-run exit
231
+ if (isDryRun) {
232
+ console.log(`
233
+ **Dry-run mode**: No changes made.
234
+ Manifest: ${sessionFolder}/cleanup-manifest.json
235
+ `)
236
+ return
237
+ }
238
+
239
+ // User confirmation
240
+ const selection = AskUser({
241
+ questions: [
242
+ {
243
+ question: "Which categories to clean?",
244
+ header: "Categories",
245
+ multiSelect: true,
246
+ options: [
247
+ { label: "Sessions", description: `${manifest.summary.by_category.stale_sessions} stale sessions` },
248
+ { label: "Documents", description: `${manifest.summary.by_category.drifted_documents} drifted docs` },
249
+ { label: "Dead Code", description: `${manifest.summary.by_category.dead_code} unused files` }
250
+ ]
251
+ },
252
+ {
253
+ question: "Risk level?",
254
+ header: "Risk",
255
+ options: [
256
+ { label: "Low only", description: "Safest (Recommended)" },
257
+ { label: "Low + Medium", description: "Includes likely unused" },
258
+ { label: "All", description: "Aggressive" }
259
+ ]
260
+ }
261
+ ]
262
+ })
263
+ ```
264
+
265
+ ---
266
+
267
+ ### Phase 4: Execution
268
+
269
+ ```javascript
270
+ const riskFilter = {
271
+ 'Low only': ['low'],
272
+ 'Low + Medium': ['low', 'medium'],
273
+ 'All': ['low', 'medium', 'high']
274
+ }[selection.risk]
275
+
276
+ // Collect items to clean
277
+ const items = []
278
+ if (selection.categories.includes('Sessions')) {
279
+ items.push(...manifest.discoveries.stale_sessions.filter(s => riskFilter.includes(s.risk)))
280
+ }
281
+ if (selection.categories.includes('Documents')) {
282
+ items.push(...manifest.discoveries.drifted_documents.filter(d => riskFilter.includes(d.risk)))
283
+ }
284
+ if (selection.categories.includes('Dead Code')) {
285
+ items.push(...manifest.discoveries.dead_code.filter(c => riskFilter.includes(c.risk)))
286
+ }
287
+
288
+ const results = { staged: [], deleted: [], failed: [], skipped: [] }
289
+
290
+ // Validate and stage
291
+ for (const item of items) {
292
+ const validation = validatePath(item.path)
293
+ if (!validation.valid) {
294
+ results.skipped.push({ path: item.path, reason: validation.reason })
295
+ continue
296
+ }
297
+
298
+ if (!fileExists(item.path) && !dirExists(item.path)) {
299
+ results.skipped.push({ path: item.path, reason: 'Not found' })
300
+ continue
301
+ }
302
+
303
+ try {
304
+ const trashTarget = `${trashFolder}/${item.path.replace(/\//g, '_')}`
305
+ bash(`mv "${item.path}" "${trashTarget}"`)
306
+ results.staged.push({ path: item.path, trashPath: trashTarget })
307
+ } catch (e) {
308
+ results.failed.push({ path: item.path, error: e.message })
309
+ }
310
+ }
311
+
312
+ // Permanent deletion
313
+ for (const staged of results.staged) {
314
+ try {
315
+ bash(`rm -rf "${staged.trashPath}"`)
316
+ results.deleted.push(staged.path)
317
+ } catch (e) {
318
+ console.error(`Failed: ${staged.path}`)
319
+ }
320
+ }
321
+
322
+ // Cleanup empty trash
323
+ bash(`rmdir "${trashFolder}" 2>/dev/null || true`)
324
+
325
+ // Report
326
+ console.log(`
327
+ ## Cleanup Complete
328
+
329
+ **Deleted**: ${results.deleted.length}
330
+ **Failed**: ${results.failed.length}
331
+ **Skipped**: ${results.skipped.length}
332
+
333
+ ### Deleted
334
+ ${results.deleted.map(p => `- ${p}`).join('\n') || '(none)'}
335
+
336
+ ${results.failed.length > 0 ? `### Failed\n${results.failed.map(f => `- ${f.path}: ${f.error}`).join('\n')}` : ''}
337
+
338
+ Report: ${sessionFolder}/cleanup-report.json
339
+ `)
340
+
341
+ Write(`${sessionFolder}/cleanup-report.json`, JSON.stringify({
342
+ timestamp: getUtc8ISOString(),
343
+ results,
344
+ summary: {
345
+ deleted: results.deleted.length,
346
+ failed: results.failed.length,
347
+ skipped: results.skipped.length
348
+ }
349
+ }, null, 2))
350
+ ```
351
+
352
+ ---
353
+
354
+ ## Session Folder
355
+
356
+ ```
357
+ .workflow/.clean/clean-{YYYY-MM-DD}/
358
+ ├── mainline-profile.json # Git history analysis
359
+ ├── cleanup-manifest.json # Discovery results
360
+ ├── cleanup-report.json # Execution results
361
+ └── .trash/ # Staging area (temporary)
362
+ ```
363
+
364
+ ## Risk Levels
365
+
366
+ | Risk | Description | Examples |
367
+ |------|-------------|----------|
368
+ | **Low** | Safe to delete | Empty sessions, scratchpad files |
369
+ | **Medium** | Likely unused | Orphan files, old archives |
370
+ | **High** | May have dependencies | Files with some imports |
371
+
372
+ ## Security Features
373
+
374
+ | Feature | Protection |
375
+ |---------|------------|
376
+ | Path Validation | Whitelist directories, reject traversal |
377
+ | Staged Deletion | Move to .trash before permanent delete |
378
+ | Dangerous Patterns | Block system dirs, node_modules, .git |
379
+
380
+ ## Iteration Flow
381
+
382
+ ```
383
+ First Call (/prompts:clean):
384
+ ├─ Detect mainline from git history
385
+ ├─ Discover stale artifacts via subagent
386
+ ├─ Display summary, await user selection
387
+ └─ Execute cleanup with staging
388
+
389
+ Dry-Run (/prompts:clean --dry-run):
390
+ ├─ All phases except execution
391
+ └─ Manifest saved for review
392
+
393
+ Focused (/prompts:clean FOCUS="auth"):
394
+ └─ Discovery limited to specified area
395
+ ```
396
+
397
+ ## Error Handling
398
+
399
+ | Situation | Action |
400
+ |-----------|--------|
401
+ | No git repo | Use file timestamps only |
402
+ | Agent timeout | Retry once with prompt, then abort |
403
+ | Path validation fail | Skip item, report reason |
404
+ | Manifest parse error | Abort with error |
405
+ | Empty discovery | Report "codebase is clean" |
406
+
407
+ ---
408
+
409
+ **Now execute cleanup workflow** with focus: $FOCUS