agent-watch 1.0.0 → 1.1.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +332 -45
  3. package/dist/cli.cjs +101 -73
  4. package/dist/cli.cjs.map +1 -1
  5. package/dist/cli.js +101 -73
  6. package/dist/cli.js.map +1 -1
  7. package/dist/commands/run.d.ts +2 -1
  8. package/dist/commands/run.d.ts.map +1 -1
  9. package/dist/constants.d.ts +7 -0
  10. package/dist/constants.d.ts.map +1 -1
  11. package/dist/index.cjs +5 -4
  12. package/dist/index.d.cts +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +2 -2
  16. package/dist/prompts/agent-file-creation.d.ts +5 -0
  17. package/dist/prompts/agent-file-creation.d.ts.map +1 -0
  18. package/dist/prompts/agent-file-update.d.ts +6 -0
  19. package/dist/prompts/agent-file-update.d.ts.map +1 -0
  20. package/dist/prompts/index.d.ts +4 -0
  21. package/dist/prompts/index.d.ts.map +1 -0
  22. package/dist/prompts/session-analysis.d.ts +6 -0
  23. package/dist/prompts/session-analysis.d.ts.map +1 -0
  24. package/dist/sessions-B4LKRElS.js +655 -0
  25. package/dist/sessions-B4LKRElS.js.map +1 -0
  26. package/dist/sessions-B8sOtKjE.cjs +580 -0
  27. package/dist/sessions-B8sOtKjE.cjs.map +1 -0
  28. package/dist/sessions-BJMOAv46.cjs +812 -0
  29. package/dist/sessions-BJMOAv46.cjs.map +1 -0
  30. package/dist/sessions-BOdRsGPL.js +656 -0
  31. package/dist/sessions-BOdRsGPL.js.map +1 -0
  32. package/dist/sessions-BRKqjffL.cjs +803 -0
  33. package/dist/sessions-BRKqjffL.cjs.map +1 -0
  34. package/dist/sessions-Ba9MsXSC.js +656 -0
  35. package/dist/sessions-Ba9MsXSC.js.map +1 -0
  36. package/dist/sessions-BpZgNhE-.js +646 -0
  37. package/dist/sessions-BpZgNhE-.js.map +1 -0
  38. package/dist/sessions-COk9zTav.js +665 -0
  39. package/dist/sessions-COk9zTav.js.map +1 -0
  40. package/dist/sessions-DLXk_tQZ.cjs +812 -0
  41. package/dist/sessions-DLXk_tQZ.cjs.map +1 -0
  42. package/dist/sessions-DdCr9WvU.js +665 -0
  43. package/dist/sessions-DdCr9WvU.js.map +1 -0
  44. package/dist/sessions-Di0snUK6.cjs +793 -0
  45. package/dist/sessions-Di0snUK6.cjs.map +1 -0
  46. package/dist/sessions-Dk0l8m0S.cjs +793 -0
  47. package/dist/sessions-Dk0l8m0S.cjs.map +1 -0
  48. package/dist/sessions-Dqd68o3V.cjs +802 -0
  49. package/dist/sessions-Dqd68o3V.cjs.map +1 -0
  50. package/dist/sessions-Oljuf4d8.js +646 -0
  51. package/dist/sessions-Oljuf4d8.js.map +1 -0
  52. package/dist/sessions-h-ow_AGT.js +421 -0
  53. package/dist/sessions-h-ow_AGT.js.map +1 -0
  54. package/dist/sessions-kuk4Rkbp.cjs +803 -0
  55. package/dist/sessions-kuk4Rkbp.cjs.map +1 -0
  56. package/dist/utils/debug.d.ts +29 -0
  57. package/dist/utils/debug.d.ts.map +1 -0
  58. package/dist/utils/sessions/extractors/claude-code.d.ts +12 -0
  59. package/dist/utils/sessions/extractors/claude-code.d.ts.map +1 -0
  60. package/dist/utils/sessions/extractors/copilot-chat.d.ts +12 -0
  61. package/dist/utils/sessions/extractors/copilot-chat.d.ts.map +1 -0
  62. package/dist/utils/sessions/extractors/copilot-cli.d.ts +11 -0
  63. package/dist/utils/sessions/extractors/copilot-cli.d.ts.map +1 -0
  64. package/dist/utils/sessions/index.d.ts +12 -0
  65. package/dist/utils/sessions/index.d.ts.map +1 -0
  66. package/dist/utils/sessions/state.d.ts +14 -0
  67. package/dist/utils/sessions/state.d.ts.map +1 -0
  68. package/dist/utils/sessions/summarize.d.ts +8 -0
  69. package/dist/utils/sessions/summarize.d.ts.map +1 -0
  70. package/dist/utils/sessions/types.d.ts +61 -0
  71. package/dist/utils/sessions/types.d.ts.map +1 -0
  72. package/dist/utils/sessions/utils.d.ts +19 -0
  73. package/dist/utils/sessions/utils.d.ts.map +1 -0
  74. package/dist/utils/sessions.d.ts +1 -1
  75. package/dist/utils/sessions.d.ts.map +1 -1
  76. package/package.json +3 -6
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Enhance session extraction architecture with tool-specific extractors for Claude Code, Copilot Chat, and Copilot CLI. Refactor session handling code for better maintainability and add comprehensive documentation.
8
+
9
+ ## 1.0.1
10
+
11
+ ### Patch Changes
12
+
13
+ - Add debug mode with --debug flag for troubleshooting, improve documentation, and remove obsolete workflows
14
+
3
15
  All notable changes to this project will be documented in this file.
4
16
 
5
17
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
package/README.md CHANGED
@@ -1,95 +1,382 @@
1
1
  # Agent Watch
2
2
 
3
- CLI tool that uses git hooks to keep your AI agent configuration files in sync with your codebase. It watches for commits or pushes, gathers context from git changes and chat sessions, and automatically updates your agent files.
3
+ **Keep your AI agents in sync with your evolving codebaseautomatically.**
4
4
 
5
- ## Install
5
+ Agent Watch is a CLI tool that captures knowledge from your development workflow—git commits, code changes, and AI chat sessions—and intelligently updates your AI agent configuration files. Stop manually copying patterns from chat sessions. Stop forgetting to update CLAUDE.md or Copilot instructions. Let agent-watch learn from your work and keep your AI agents informed.
6
6
 
7
+ ## Why Agent Watch?
8
+
9
+ ### The Problem
10
+ You're having productive conversations with Claude Code, GitHub Copilot, and other AI assistants. They help you establish patterns, conventions, and best practices. But this knowledge stays trapped in chat history. Your agent configuration files (CLAUDE.md, copilot-instructions.md, etc.) become outdated within days.
11
+
12
+ **Result:** Your AI assistants keep making the same mistakes. They forget your team's conventions. You waste time repeating yourself.
13
+
14
+ ### The Solution
15
+ Agent Watch automatically:
16
+ - ✅ **Extracts patterns** from your Claude Code, Copilot Chat, and Copilot CLI sessions
17
+ - ✅ **Summarizes learnings** using AI to distill actionable conventions
18
+ - ✅ **Updates all agent files** in one atomic operation via git hooks
19
+ - ✅ **Deduplicates intelligently** to never reprocess the same sessions
20
+ - ✅ **Maintains consistency** across all your AI agent configuration files
21
+
22
+ ### Business Value
23
+ - 🚀 **Faster onboarding**: New team members get AI assistants that know your codebase conventions from day one
24
+ - 🎯 **Consistent code quality**: AI agents follow your established patterns automatically
25
+ - ⏱️ **Time savings**: Stop manually updating agent files or repeating yourself in chat
26
+ - 📈 **Knowledge retention**: Capture architectural decisions and patterns from every conversation
27
+ - 🤝 **Team alignment**: Share learnings across the team through version-controlled agent files
28
+
29
+ ---
30
+
31
+ ## Quick Start
32
+
33
+ ### 1. Install
34
+
35
+ **Global installation** (recommended):
7
36
  ```bash
8
37
  npm install -g agent-watch
9
38
  ```
10
39
 
11
- Or run directly:
40
+ **Or as a dev dependency** (for team consistency):
41
+ ```bash
42
+ npm install -D agent-watch
43
+ # or
44
+ pnpm add -D agent-watch
45
+ ```
12
46
 
47
+ **Or run directly** without installation:
13
48
  ```bash
14
49
  npx agent-watch init
15
50
  ```
16
51
 
17
- ## Quick start
52
+ ### 2. Initialize in Your Project
18
53
 
19
54
  ```bash
20
55
  cd your-project
21
56
  agent-watch init
22
57
  ```
23
58
 
24
- The `init` command walks you through an interactive setup:
59
+ The interactive setup wizard will:
60
+ 1. **Detect existing agent files** (CLAUDE.md, copilot-instructions.md, etc.)
61
+ 2. **Let you select which files to manage** (space to toggle, enter to confirm)
62
+ 3. **Ask about git context** - include commit messages and file changes?
63
+ 4. **Ask about chat sessions** - extract patterns from AI conversations?
64
+ 5. **Let you choose AI tools** - Claude Code, Copilot Chat, Copilot CLI?
65
+ 6. **Pick when to run** - after `git commit` or before `git push`?
66
+ 7. **Install the git hook** automatically
67
+
68
+ Your configuration is saved to `.agent-watch/config.json`.
69
+
70
+ ### 3. Start Coding Normally
71
+
72
+ That's it! Now whenever you commit code:
73
+
74
+ ```bash
75
+ git add .
76
+ git commit -m "feat: add user authentication"
77
+ # agent-watch runs automatically
78
+ # ✅ Extracts latest 3 sessions from each AI tool
79
+ # ✅ Generates summaries of patterns discussed
80
+ # ✅ Updates CLAUDE.md, copilot-instructions.md, etc.
81
+ ```
82
+
83
+ ---
84
+
85
+ ## How It Works
86
+
87
+ ### Architecture Overview
88
+
89
+ ```
90
+ ┌─────────────────────────────────────────────────────────────┐
91
+ │ 1. GIT COMMIT TRIGGERED │
92
+ │ User commits code → git hook activates agent-watch │
93
+ └─────────────────────────────────────────────────────────────┘
94
+
95
+ ┌─────────────────────────────────────────────────────────────┐
96
+ │ 2. EXTRACT LATEST SESSIONS (3 per tool) │
97
+ │ ├─ Claude Code: ~/.claude/projects/<hash>/ │
98
+ │ ├─ Copilot Chat: ~/Library/.../workspaceStorage/ │
99
+ │ └─ Copilot CLI: ~/.copilot/session-state/ │
100
+ └─────────────────────────────────────────────────────────────┘
101
+
102
+ ┌─────────────────────────────────────────────────────────────┐
103
+ │ 3. SUMMARIZE PATTERNS (via GitHub Copilot CLI) │
104
+ │ For each session: │
105
+ │ • Extract human messages + AI's final response │
106
+ │ • Ask Copilot: "What patterns/rules were discussed?" │
107
+ │ • Get concise summary of conventions │
108
+ └─────────────────────────────────────────────────────────────┘
109
+
110
+ ┌─────────────────────────────────────────────────────────────┐
111
+ │ 4. COLLECT GIT CONTEXT │
112
+ │ • Files changed in commit │
113
+ │ • Commit message │
114
+ │ • Diff statistics │
115
+ └─────────────────────────────────────────────────────────────┘
116
+
117
+ ┌─────────────────────────────────────────────────────────────┐
118
+ │ 5. SINGLE ATOMIC UPDATE (copilot --yolo) │
119
+ │ Send one prompt with: │
120
+ │ • All session summaries │
121
+ │ • Git context │
122
+ │ • Paths to all agent files │
123
+ │ │
124
+ │ Copilot reads and updates all files together, │
125
+ │ maintaining consistency across CLAUDE.md, │
126
+ │ copilot-instructions.md, AGENTS.md, etc. │
127
+ └─────────────────────────────────────────────────────────────┘
128
+ ```
129
+
130
+ ### Smart Deduplication
25
131
 
26
- 1. **Select agent files** - auto-detects existing files and lets you pick which ones to manage (space to toggle, enter to confirm)
27
- 2. **Git context** - choose whether to use commit messages and chat sessions when updating files
28
- 3. **Hook trigger** - pick when to run: after `git commit` or before `git push`
29
- 4. **AI agents** - select which agent integrations to enable (GitHub Copilot CLI, more coming)
132
+ Agent Watch tracks which sessions have been processed **per tool**:
30
133
 
31
- Your choices are saved to `.agent-watch.json` in the project root.
134
+ ```json
135
+ {
136
+ "processedSessions": {
137
+ "claude-code": ["session-1", "session-2"],
138
+ "github-copilot-chat": ["chat-1", "chat-2"],
139
+ "github-copilot-cli": ["cli-1", "cli-2"]
140
+ }
141
+ }
142
+ ```
143
+
144
+ **You'll never waste time reprocessing the same conversations.**
145
+
146
+ ### Smart Filtering
147
+
148
+ Agent Watch automatically **skips analysis** when only these files change:
149
+ - Documentation (README.md, CHANGELOG.md, etc.)
150
+ - Config files (.gitignore, tsconfig.json, etc.)
151
+ - Lock files (package-lock.json, pnpm-lock.yaml, etc.)
152
+ - Agent files themselves (CLAUDE.md, copilot-instructions.md, etc.)
153
+
154
+ **Your workflow stays fast.**
155
+
156
+ ---
157
+
158
+ ## Supported AI Tools
159
+
160
+ | AI Tool | What Gets Extracted | Where Sessions Are Stored |
161
+ | ----------------------- | ------------------------------ | ----------------------------------------------------- |
162
+ | **Claude Code** | Conversations from CLI and IDE | `~/.claude/projects/<hash>/` |
163
+ | **GitHub Copilot Chat** | Chat sessions in VS Code | `~/Library/.../workspaceStorage/<hash>/chatSessions/` |
164
+ | **GitHub Copilot CLI** | Terminal chat sessions | `~/.copilot/session-state/` |
165
+
166
+ **More tools coming:** Cursor, Windsurf, Cline support is on the roadmap.
32
167
 
33
- ## Supported agent files
168
+ ---
34
169
 
35
- | File | Agent |
36
- | --------------------------------- | -------------- |
37
- | `CLAUDE.md` | Claude Code |
38
- | `.github/copilot-instructions.md` | GitHub Copilot |
39
- | `copilot-instructions.md` | GitHub Copilot |
40
- | `AGENTS.md` / `agents.md` | Generic |
41
- | `.cursorrules` / `.cursor/rules` | Cursor |
42
- | `.windsurfrules` | Windsurf |
43
- | `.clinerules` | Cline |
170
+ ## Supported Agent Files
44
171
 
45
- ## How it works
172
+ Agent Watch can manage these configuration files:
46
173
 
47
- After running `agent-watch init`:
174
+ | File | AI Tool |
175
+ | --------------------------------- | ------------------- |
176
+ | `CLAUDE.md` | Claude Code |
177
+ | `.github/copilot-instructions.md` | GitHub Copilot |
178
+ | `AGENTS.md` / `agents.md` | Generic (all tools) |
179
+ | `.cursorrules` / `.cursor/rules` | Cursor |
180
+ | `.windsurfrules` | Windsurf |
181
+ | `.clinerules` | Cline |
48
182
 
49
- - A git hook is installed (or instructions are provided if you use lefthook/husky)
50
- - On each commit or push (depending on your config), agent-watch gathers context from:
51
- - Changed files in the commit
52
- - Git commit messages
53
- - Chat sessions from supported AI tools
54
- - It uses this context to update your selected agent configuration files
183
+ **You choose which files to manage during setup.**
55
184
 
56
- **Smart filtering**: agent-watch automatically skips running when only documentation or config files are modified (like README.md, .gitignore, lock files, etc.), keeping your workflow fast.
185
+ ---
57
186
 
58
187
  ## Configuration
59
188
 
60
- The `.agent-watch.json` config file:
189
+ After running `agent-watch init`, your config is stored in `.agent-watch/config.json`:
61
190
 
62
191
  ```json
63
192
  {
64
193
  "version": 1,
65
194
  "agentFiles": ["CLAUDE.md", ".github/copilot-instructions.md"],
66
- "useGitContext": true,
195
+ "watchFileChanges": true,
196
+ "includeChatSession": true,
67
197
  "hookTrigger": "commit",
68
- "agents": ["github-copilot-cli"]
198
+ "agents": ["claude-code", "github-copilot-chat", "github-copilot-cli"]
69
199
  }
70
200
  ```
71
201
 
72
- ## Git hook integration
202
+ ### Configuration Options
203
+
204
+ | Option | Type | Description |
205
+ | -------------------- | -------------------- | --------------------------------------- |
206
+ | `agentFiles` | `string[]` | Which agent files to update |
207
+ | `watchFileChanges` | `boolean` | Include git commit context |
208
+ | `includeChatSession` | `boolean` | Extract and summarize chat sessions |
209
+ | `hookTrigger` | `"commit" \| "push"` | When to run agent-watch |
210
+ | `agents` | `string[]` | Which AI tools to extract sessions from |
211
+
212
+ ---
213
+
214
+ ## Advanced Usage
215
+
216
+ ### Debug Mode
217
+
218
+ See what agent-watch is doing under the hood:
219
+
220
+ ```bash
221
+ agent-watch run --debug
222
+ ```
223
+
224
+ This creates `.agent-watch/debug/` with:
225
+ - Raw session extractions
226
+ - Generated summaries
227
+ - Final prompt sent to Copilot
228
+ - Copilot's response
229
+
230
+ **Useful for troubleshooting or understanding how summaries are generated.**
231
+
232
+ ### Manual Run
233
+
234
+ Trigger agent-watch without committing:
235
+
236
+ ```bash
237
+ agent-watch run
238
+ ```
239
+
240
+ ### Git Hook Integration
241
+
242
+ Agent Watch automatically detects and integrates with:
243
+
244
+ **Lefthook** - Adds to `lefthook.yml`:
245
+ ```yaml
246
+ post-commit:
247
+ commands:
248
+ agent-watch:
249
+ run: npx agent-watch run
250
+ ```
251
+
252
+ **Husky** - Creates hook:
253
+ ```bash
254
+ npx husky add .husky/post-commit "npx agent-watch run"
255
+ ```
256
+
257
+ **Direct** - Installs to `.git/hooks/post-commit` if no hook manager detected.
258
+
259
+ ---
260
+
261
+ ## Real-World Example
262
+
263
+ ### Before Agent Watch
264
+
265
+ You're building a React app. Over several days, you have these conversations with Claude Code:
266
+
267
+ 1. **Monday**: Establish that all API calls should use React Query
268
+ 2. **Tuesday**: Decide to use Zod for validation schemas
269
+ 3. **Wednesday**: Create a pattern for error boundaries
270
+ 4. **Thursday**: New team member asks Claude to fetch data with `fetch()` (Claude suggests it because CLAUDE.md is outdated)
271
+
272
+ **Problem:** Your conventions are lost in chat history. New code violates established patterns.
273
+
274
+ ### After Agent Watch
275
+
276
+ Every time you commit:
277
+
278
+ 1. **Monday commit**: CLAUDE.md updated with "Use React Query for all API calls"
279
+ 2. **Tuesday commit**: CLAUDE.md updated with "Validate with Zod schemas"
280
+ 3. **Wednesday commit**: CLAUDE.md updated with error boundary pattern
281
+ 4. **Thursday**: New team member's Claude Code already knows to use React Query (reads CLAUDE.md)
282
+
283
+ **Result:** Consistency maintained automatically. Knowledge compounds.
284
+
285
+ ---
73
286
 
74
- agent-watch detects your existing hook manager:
287
+ ## FAQ
75
288
 
76
- - **Lefthook** - prints the config to add to `lefthook.yml`
77
- - **Husky** - prints the `npx husky add` command to run
78
- - **No hook manager** - installs directly to `.git/hooks/`
289
+ **Q: Does this require GitHub Copilot subscription?**
290
+ A: Yes, for the summarization feature. Agent Watch uses `copilot --yolo` to intelligently update agent files. However, session extraction works independently.
79
291
 
80
- The hook is idempotent and can be safely re-run.
292
+ **Q: Will this commit the updated agent files automatically?**
293
+ A: No. Agent Watch updates the files, but you'll see them as unstaged changes. Review and commit them when ready.
81
294
 
82
- ## Programmatic API
295
+ **Q: What if I don't want to extract from all tools?**
296
+ A: During `agent-watch init`, select only the tools you want. You can also edit `.agent-watch/config.json` later.
83
297
 
84
- You can also use agent-watch as a library:
298
+ **Q: Can I use this with a monorepo?**
299
+ A: Yes! Run `agent-watch init` in each package that has its own agent files.
85
300
 
86
- ```ts
87
- import { loadConfig, detectAgentFiles, KNOWN_AGENT_FILES } from "agent-watch"
301
+ **Q: What about privacy? Are my chat sessions sent anywhere?**
302
+ A: No external services. Everything runs locally. Sessions are summarized via your local Copilot CLI installation.
88
303
 
89
- const config = loadConfig("./my-project")
90
- const files = detectAgentFiles("./my-project")
304
+ **Q: Can I customize the summarization prompt?**
305
+ A: Not currently, but this is on the roadmap. Open an issue if you need this feature.
306
+
307
+ ---
308
+
309
+ ## Roadmap
310
+
311
+ - [ ] Support for more AI tools (Cursor, Windsurf, Cline)
312
+ - [ ] Customizable summarization prompts
313
+ - [ ] Team-wide deduplication (shared processed sessions state)
314
+ - [ ] Export/import of agent file versions
315
+ - [ ] Integration with CI/CD pipelines
316
+ - [ ] Web dashboard for visualizing pattern evolution
317
+
318
+ ---
319
+
320
+ ## Contributing
321
+
322
+ We welcome contributions! To get started:
323
+
324
+ 1. Fork the repository
325
+ 2. Create a feature branch: `git checkout -b feature/my-feature`
326
+ 3. Make your changes
327
+ 4. Add tests if applicable
328
+ 5. Run tests: `pnpm test:ci`
329
+ 6. Submit a pull request
330
+
331
+ ### Development Setup
332
+
333
+ ```bash
334
+ git clone https://github.com/surnr/agent-watch.git
335
+ cd agent-watch
336
+ pnpm install
337
+ pnpm build
338
+ pnpm link --global
91
339
  ```
92
340
 
341
+ Now you can test your changes with `agent-watch` commands.
342
+
343
+ ---
344
+
345
+ ## Troubleshooting
346
+
347
+ **Issue: "No agent files configured"**
348
+ **Solution:** Run `agent-watch init` to set up configuration.
349
+
350
+ **Issue: "copilot: command not found"**
351
+ **Solution:** Install GitHub Copilot CLI: `npm install -g @githubnext/github-copilot-cli`
352
+
353
+ **Issue: Sessions not being extracted**
354
+ **Solution:**
355
+ 1. Check that you have chat sessions in the expected locations
356
+ 2. Run `agent-watch run --debug` to see what's happening
357
+ 3. Verify your tool selections in `.agent-watch/config.json`
358
+
359
+ **Issue: Agent files not updating**
360
+ **Solution:**
361
+ 1. Ensure Copilot CLI is authenticated: `copilot auth`
362
+ 2. Check `.agent-watch/debug/` logs if debug mode is enabled
363
+ 3. Verify agent file paths in config are correct
364
+
365
+ ---
366
+
93
367
  ## License
94
368
 
95
- MIT
369
+ MIT License - see [LICENSE](LICENSE) file for details.
370
+
371
+ ---
372
+
373
+ ## Support
374
+
375
+ - 🐛 **Bug reports:** [GitHub Issues](https://github.com/surnr/agent-watch/issues)
376
+ - 💡 **Feature requests:** [GitHub Discussions](https://github.com/surnr/agent-watch/discussions)
377
+ - 📖 **Documentation:** Check the [docs](./docs) folder
378
+ - ⭐ **Star us on GitHub** if you find this useful!
379
+
380
+ ---
381
+
382
+ **Built with ❤️ for developers who believe AI assistants should remember your conversations.**
package/dist/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- const require_sessions = require('./sessions-_HBb3nIW.cjs');
2
+ const require_sessions = require('./sessions-Di0snUK6.cjs');
3
3
  let node_module = require("node:module");
4
4
  let commander = require("commander");
5
5
  let _inquirer_prompts = require("@inquirer/prompts");
@@ -593,6 +593,58 @@ async function initCommand() {
593
593
  require_sessions.logger.blank();
594
594
  }
595
595
 
596
+ //#endregion
597
+ //#region src/utils/debug.ts
598
+ /**
599
+ * Global debug mode flag
600
+ */
601
+ let debugMode = false;
602
+ /**
603
+ * Set the debug mode for the current run
604
+ */
605
+ function setDebugMode(enabled) {
606
+ debugMode = enabled;
607
+ }
608
+ /**
609
+ * Generate a timestamp for log filenames
610
+ */
611
+ function getTimestamp() {
612
+ return (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
613
+ }
614
+ /**
615
+ * Ensure the debug logs directory exists
616
+ */
617
+ function ensureDebugDir(projectRoot) {
618
+ const debugDir = (0, node_path.join)(projectRoot, require_sessions.AGENT_WATCH_DIR, require_sessions.DEBUG_LOGS_DIR);
619
+ if (!(0, node_fs.existsSync)(debugDir)) (0, node_fs.mkdirSync)(debugDir, { recursive: true });
620
+ return debugDir;
621
+ }
622
+ /**
623
+ * Write debug content to a file in the debug logs directory
624
+ */
625
+ function writeDebugLog(projectRoot, filename, content) {
626
+ if (!debugMode) return;
627
+ (0, node_fs.writeFileSync)((0, node_path.join)(ensureDebugDir(projectRoot), `${getTimestamp()}_${filename}`), content, "utf-8");
628
+ }
629
+ /**
630
+ * Log the context built from file changes and chat sessions
631
+ */
632
+ function logContext(projectRoot, context) {
633
+ writeDebugLog(projectRoot, "context.txt", context);
634
+ }
635
+ /**
636
+ * Log the prompt sent to copilot
637
+ */
638
+ function logCopilotPrompt(projectRoot, agentFile, prompt) {
639
+ writeDebugLog(projectRoot, `prompt_${agentFile.replace(/[/\\]/g, "_")}.txt`, prompt);
640
+ }
641
+ /**
642
+ * Log the response from copilot
643
+ */
644
+ function logCopilotResponse(projectRoot, agentFile, response) {
645
+ writeDebugLog(projectRoot, `response_${agentFile.replace(/[/\\]/g, "_")}.txt`, response);
646
+ }
647
+
596
648
  //#endregion
597
649
  //#region src/commands/run.ts
598
650
  /**
@@ -635,12 +687,12 @@ function getModifiedFiles() {
635
687
  }
636
688
  }
637
689
  /**
638
- * Check if a file path should be ignored (doesn't trigger agent-watch analysis)
690
+ * Check if a file path should be ignored
639
691
  */
640
692
  function shouldIgnoreFile(filePath) {
641
- const normalizedPath = filePath.replace(/\\/g, "/");
693
+ const normalizedPath = filePath.replaceAll("\\", "/");
642
694
  for (const pattern of require_sessions.IGNORED_FILE_PATTERNS) {
643
- const normalizedPattern = pattern.replace(/\\/g, "/");
695
+ const normalizedPattern = pattern.replaceAll("\\", "/");
644
696
  if (normalizedPath === normalizedPattern) return true;
645
697
  if (normalizedPath.startsWith(`${normalizedPattern}/`)) return true;
646
698
  if (normalizedPath.split("/").pop() === normalizedPattern) return true;
@@ -655,49 +707,28 @@ function shouldSkipAnalysis(modifiedFiles) {
655
707
  return modifiedFiles.every(shouldIgnoreFile);
656
708
  }
657
709
  /**
658
- * Use Copilot CLI to intelligently update agent file content
710
+ * Format git context as a readable string
659
711
  */
660
- function updateAgentFileWithCopilot(projectRoot, context, agentFilePath, currentContent) {
661
- try {
662
- const output = (0, node_child_process.execSync)(`copilot -p "${`You are maintaining ${agentFilePath}, a living document of patterns, conventions, and code rules.
663
-
664
- Your task:
665
- 1. Read the CURRENT content of this file carefully
666
- 2. Analyze the RECENT changes and conversations below
667
- 3. Determine if there are new patterns, rules, or conventions to document
668
- 4. If updates are needed, output the COMPLETE UPDATED file content
669
- 5. If no meaningful updates needed, output exactly: NO_UPDATE
670
-
671
- Guidelines:
672
- - Intelligently merge new insights into existing sections
673
- - Update or refine existing rules if patterns have evolved
674
- - Remove outdated information
675
- - Keep it concise - no code snippets unless absolutely necessary
676
- - Maintain the file's existing structure and tone
677
- - Focus on patterns, conventions, and learnings - not changelogs
678
-
679
- CURRENT FILE CONTENT:
680
- ${currentContent}
681
-
682
- RECENT CONTEXT:
683
- ${context}
684
-
685
- Output the complete updated file, or NO_UPDATE if nothing significant to add:`.replaceAll("\"", String.raw`\"`)}" -s`, {
686
- cwd: projectRoot,
687
- encoding: "utf-8",
688
- stdio: "pipe",
689
- timeout: 9e4
690
- }).trim();
691
- if (output === "NO_UPDATE" || output.length === 0 || output === currentContent) return null;
692
- return output;
693
- } catch {
694
- return null;
695
- }
712
+ function formatGitContext(commitMessage, modifiedFiles, diffStats) {
713
+ const parts = [];
714
+ if (commitMessage) parts.push(`Commit message: ${commitMessage}`);
715
+ if (modifiedFiles.length > 0) parts.push(`Files changed: ${modifiedFiles.join(", ")}`);
716
+ if (diffStats) parts.push(`Diff stats:\n${diffStats}`);
717
+ return parts.join("\n\n");
718
+ }
719
+ /**
720
+ * Escape prompt for safe shell execution
721
+ */
722
+ function escapeShellPrompt(prompt) {
723
+ return prompt.replaceAll("\"", String.raw`\"`);
696
724
  }
697
725
  /**
698
726
  * Run command - update agent files with extracted patterns and learnings
727
+ * New approach: Collect summaries from all tools, then use single yolo command
699
728
  */
700
- async function runCommand() {
729
+ async function runCommand(debug = false) {
730
+ setDebugMode(debug);
731
+ if (debug) require_sessions.logger.info("Debug mode enabled - logs will be saved to .agent-watch/debug/");
701
732
  const gitRoot = findGitRoot(process.cwd());
702
733
  if (!gitRoot) {
703
734
  require_sessions.logger.error("Not inside a git repository");
@@ -712,46 +743,43 @@ async function runCommand() {
712
743
  require_sessions.logger.warn("No agent files configured");
713
744
  return;
714
745
  }
715
- const contextParts = [];
746
+ let gitContext = "";
716
747
  if (config.watchFileChanges) {
717
748
  const modifiedFiles = getModifiedFiles();
718
749
  if (shouldSkipAnalysis(modifiedFiles)) {
719
750
  require_sessions.logger.info("Skipping analysis - only config/documentation files changed");
720
751
  return;
721
752
  }
722
- const commitMessage = getCommitMessage();
723
- const diffStats = getGitDiffStats();
724
- if (modifiedFiles.length > 0) {
725
- const fileContext = [
726
- commitMessage ? `Commit: ${commitMessage}` : "",
727
- `Files changed: ${modifiedFiles.join(", ")}`,
728
- diffStats ? `Stats:\n${diffStats}` : ""
729
- ].filter(Boolean).join("\n");
730
- contextParts.push(fileContext);
731
- }
753
+ gitContext = formatGitContext(getCommitMessage(), modifiedFiles, getGitDiffStats());
732
754
  }
733
- if (config.includeChatSession) {
734
- const sessionContext = require_sessions.processNewSessions(gitRoot);
735
- if (sessionContext) contextParts.push(`Conversations:\n${sessionContext}`);
736
- }
737
- if (contextParts.length === 0) {
755
+ const summaries = config.includeChatSession && config.agents.length > 0 ? require_sessions.processAllSessions(gitRoot, config.agents) : [];
756
+ if (!gitContext && summaries.length === 0) {
738
757
  require_sessions.logger.info("No new context to analyze");
739
758
  return;
740
759
  }
741
- const context = contextParts.join("\n\n");
742
- require_sessions.logger.step("Analyzing context for patterns and rules...");
743
- let updatedCount = 0;
744
- for (const filePath of config.agentFiles) {
745
- const fullPath = (0, node_path.join)(gitRoot, filePath);
746
- const updatedContent = updateAgentFileWithCopilot(gitRoot, context, filePath, (0, node_fs.readFileSync)(fullPath, "utf-8"));
747
- if (updatedContent) {
748
- (0, node_fs.writeFileSync)(fullPath, updatedContent, "utf-8");
749
- require_sessions.logger.success(`Updated ${filePath}`);
750
- updatedCount++;
751
- }
760
+ const agentFilePaths = config.agentFiles.map((f) => (0, node_path.join)(gitRoot, f));
761
+ const prompt = `Based on the following context, intelligently update the agent configuration files listed below. Only update if there are meaningful new patterns, conventions, or rules to document.
762
+
763
+ ${gitContext ? `## Git Changes\n${gitContext}\n\n` : ""}${summaries.length > 0 ? `## Pattern Summaries from Chat Sessions\n${summaries.join("\n\n")}\n\n` : ""}## Agent Files to Update
764
+ ${agentFilePaths.map((p) => `- ${p}`).join("\n")}
765
+
766
+ Read each file, analyze its current content, and update with new insights. Merge patterns intelligently, maintain existing structure, remove outdated info. Focus on patterns and conventions, not changelogs.`;
767
+ logContext(gitRoot, `${gitContext}\n\nSummaries:\n${summaries.join("\n\n")}`);
768
+ logCopilotPrompt(gitRoot, "yolo-update", prompt);
769
+ require_sessions.logger.step("Updating agent files via Copilot --yolo...");
770
+ try {
771
+ logCopilotResponse(gitRoot, "yolo-update", (0, node_child_process.execSync)(`copilot -p "${escapeShellPrompt(prompt)}" --yolo`, {
772
+ cwd: gitRoot,
773
+ encoding: "utf-8",
774
+ stdio: "pipe",
775
+ timeout: 18e4
776
+ }));
777
+ require_sessions.logger.success("Agent files updated successfully");
778
+ } catch (error) {
779
+ const errorMessage = error instanceof Error ? error.message : String(error);
780
+ require_sessions.logger.error(`Failed to update files: ${errorMessage}`);
781
+ process.exit(1);
752
782
  }
753
- if (updatedCount > 0) require_sessions.logger.success(`Updated ${updatedCount} agent file(s) with new insights`);
754
- else require_sessions.logger.info("No significant patterns found to update");
755
783
  }
756
784
 
757
785
  //#endregion
@@ -761,8 +789,8 @@ commander.program.name("agent-watch").description("Keep your AI agent configurat
761
789
  commander.program.command("init").description("Initialize agent-watch in the current project").action(async () => {
762
790
  await initCommand();
763
791
  });
764
- commander.program.command("run").description("Update agent files with recent changes and chat sessions").action(async () => {
765
- await runCommand();
792
+ commander.program.command("run").description("Update agent files with recent changes and chat sessions").option("--debug", "Enable debug mode to save all content to .agent-watch/debug/").action(async (options) => {
793
+ await runCommand(options.debug ?? false);
766
794
  });
767
795
  commander.program.parse();
768
796