s9n-devops-agent 2.0.13 → 2.0.18-dev.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/houserules.md ADDED
@@ -0,0 +1,1412 @@
1
+ # House Rules for DevOps Agent
2
+
3
+ ## 🚨 CRITICAL: File Coordination & Infrastructure Protocol (MUST FOLLOW)
4
+
5
+ **To prevent conflicts with other agents and maintain infrastructure integrity, you MUST follow this protocol:**
6
+
7
+ ### Before Editing ANY Files or Creating Infrastructure:
8
+
9
+ 1. **DECLARE YOUR INTENT FIRST**
10
+ Create a file at `.file-coordination/active-edits/<your-name>-<session>.json` with:
11
+ ```json
12
+ {
13
+ "agent": "<your-name>",
14
+ "session": "<session-id>",
15
+ "files": ["list", "of", "files", "you", "will", "edit"],
16
+ "operation": "edit",
17
+ "reason": "Brief description of what you're doing",
18
+ "declaredAt": "<current-ISO-8601-timestamp>",
19
+ "estimatedDuration": 300
20
+ }
21
+ ```
22
+
23
+ 2. **READ INFRASTRUCTURE DOCUMENTATION**
24
+ - **MUST** read `/infrastructure/infrastructure.md` before creating any servers, instances, or Docker containers
25
+ - This file contains all existing infrastructure details and prevents conflicts
26
+ - Update this file when you create new infrastructure resources
27
+
28
+ 3. **CHECK FOR CONFLICTS**
29
+ - Read ALL files in `.file-coordination/active-edits/`
30
+ - If ANY other agent has declared the same files, you must:
31
+ - **STOP IMMEDIATELY** - DO NOT proceed with any edits
32
+ - **ASK THE USER** for explicit permission before editing those files
33
+ - Inform the user which agent has declared the files and for what purpose
34
+ - WAIT for the other agent to finish, OR
35
+ - Choose different files to edit
36
+ - **CRITICAL**: Never edit files another agent has declared without explicit user confirmation
37
+
38
+ 4. **ONLY EDIT DECLARED FILES**
39
+ - Never edit files you haven't declared
40
+ - Stay within your declared scope
41
+
42
+ 5. **HOLD LOCKS FOR ENTIRE SESSION**
43
+ - Keep your declaration active for the ENTIRE session
44
+ - DO NOT release locks after committing - keep them until session closes
45
+ - Locks protect files from other agents until your changes are merged
46
+
47
+ 6. **RELEASE ONLY WHEN SESSION CLOSES**
48
+ - Delete your declaration file ONLY when:
49
+ - Session is being closed/merged, OR
50
+ - Worktree is being removed
51
+ - Move it to `.file-coordination/completed-edits/` during session closure
52
+ - Update `/infrastructure/infrastructure.md` if you created infrastructure
53
+ - **CRITICAL**: Never release locks while session is still active!
54
+
55
+ ### If You Detect a Conflict:
56
+ - **STOP IMMEDIATELY** - DO NOT proceed with any edits
57
+ - **ASK THE USER** for explicit permission before editing conflicting files
58
+ - Report the conflict to the user with details:
59
+ - Which files are in conflict
60
+ - Which agent has declared them
61
+ - What that agent is working on (from their declaration)
62
+ - Wait for user decision: override, wait, or choose alternative files
63
+ - **NEVER edit conflicting files without explicit user approval**
64
+
65
+ ### Example Workflow:
66
+ ```bash
67
+ # 1. Check if files are available (no other agent editing them)
68
+ # 2. Create your declaration in .file-coordination/active-edits/
69
+ # 3. Make your edits
70
+ # 4. Write commit message to the session-specific file
71
+ # 5. Continue working (locks stay active!)
72
+ # 6. When session closes: merge changes THEN remove declaration
73
+ ```
74
+
75
+ ### Why Locks Must Stay Active:
76
+ - **Problem**: If you release locks after committing, another agent can declare and edit the same files
77
+ - **Result**: Both sessions will conflict when merging
78
+ - **Solution**: Hold locks until session is merged and worktree removed
79
+ - **Benefit**: Prevents duplicate work and merge conflicts
80
+
81
+ **This coordination prevents wasted work and merge conflicts!**
82
+
83
+ ---
84
+
85
+ ## Architecture Decision Records (ADRs)
86
+
87
+ **We treat architectural decisions as code.**
88
+ Any "Architecturally Significant" change MUST be documented in an ADR.
89
+
90
+ **What is Architecturally Significant?**
91
+ - Adding a new persistence layer (e.g., adding Redis)
92
+ - Changing the multi-agent coordination protocol
93
+ - Adding a new major component or service
94
+ - Changing the testing strategy
95
+ - Introducing the Contract System itself
96
+
97
+ **Workflow:**
98
+ 1. **Create:** Create a new file in `adr/` named `XXXX-title-of-decision.md` (e.g., `0002-switch-to-postgres.md`).
99
+ 2. **Format:** Use the standard ADR template (Context, Decision, Consequences).
100
+ 3. **Review:** Submit as part of your PR.
101
+
102
+ ## 🚨 CRITICAL: Contract System (MUST FOLLOW)
103
+
104
+ **ADDED: 2024-12-02**
105
+
106
+ **To prevent duplicate features, conflicting changes, and wasted work, ALL coding agents MUST follow the Contract System.**
107
+
108
+ ### What is the Contract System?
109
+
110
+ The Contract System is a **single source of truth** for all project components. Before making ANY changes to:
111
+ - Database schema
112
+ - SQL queries
113
+ - API endpoints
114
+ - Third-party integrations
115
+ - Features
116
+ - Infrastructure/environment variables
117
+
118
+ **You MUST check the relevant contract file first.**
119
+
120
+ ### Contract Files Location
121
+
122
+ **All contract files are stored in:** `House_Rules_Contracts/`
123
+
124
+ | Contract File | Purpose | Check Before... |
125
+ |---------------|---------|----------------|
126
+ | `DATABASE_SCHEMA_CONTRACT.md` | Database tables, columns, indexes, migrations | Creating/modifying database schema |
127
+ | `SQL_CONTRACT.json` | Reusable SQL queries with parameters | Writing any SQL query |
128
+ | `API_CONTRACT.md` | All API endpoints and specifications | Creating/modifying API endpoints |
129
+ | `THIRD_PARTY_INTEGRATIONS.md` | External service integrations | Integrating third-party services |
130
+ | `FEATURES_CONTRACT.md` | All features and specifications | Implementing any feature |
131
+ | `INFRA_CONTRACT.md` | Environment variables and infrastructure | Adding configuration/env vars |
132
+
133
+ ### 🚨 MANDATORY Workflow for ALL Coding Agents
134
+
135
+ **BEFORE making ANY changes, you MUST:**
136
+
137
+ ```
138
+ 1. IDENTIFY what you're about to change:
139
+ - Database? → Read DATABASE_SCHEMA_CONTRACT.md
140
+ - SQL query? → Read SQL_CONTRACT.json
141
+ - API endpoint? → Read API_CONTRACT.md
142
+ - Third-party service? → Read THIRD_PARTY_INTEGRATIONS.md
143
+ - Feature? → Read FEATURES_CONTRACT.md
144
+ - Config/env var? → Read INFRA_CONTRACT.md
145
+
146
+ 2. SEARCH the contract for existing implementation:
147
+ - Does this table/query/endpoint/feature already exist?
148
+ - Can I reuse existing code instead of creating new?
149
+ - Will my change conflict with existing code?
150
+
151
+ 3. DECIDE based on what you found:
152
+
153
+ IF existing implementation found:
154
+ ✅ REUSE it - Add your module to "Used By" section
155
+ ✅ EXTEND it - If it needs enhancement
156
+ ❌ DO NOT duplicate it
157
+ ❌ DO NOT create a new version
158
+
159
+ IF no existing implementation:
160
+ ✅ CREATE new following contract template
161
+ ✅ DOCUMENT thoroughly in contract
162
+ ✅ CROSS-REFERENCE other contracts
163
+ ✅ UPDATE version number and changelog
164
+
165
+ 4. AFTER making changes:
166
+ ✅ UPDATE the relevant contract file immediately
167
+ ✅ ADD changelog entry with date
168
+ ✅ INCREMENT version number
169
+ ✅ CROSS-REFERENCE related contracts
170
+ ```
171
+
172
+ ### Why This Prevents Chaos
173
+
174
+ **Without contracts, multiple agents will:**
175
+ ❌ Create duplicate features with different names
176
+ ❌ Create duplicate API endpoints for same functionality
177
+ ❌ Create duplicate SQL queries doing the same thing
178
+ ❌ Integrate the same third-party service multiple times
179
+ ❌ Create conflicting database schema changes
180
+ ❌ Create duplicate environment variables
181
+ ❌ Overwrite each other's code
182
+ ❌ Break existing functionality unknowingly
183
+
184
+ **With contracts, agents will:**
185
+ ✅ Discover existing functionality before building
186
+ ✅ Reuse existing code instead of duplicating
187
+ ✅ Know exactly what exists and how to use it
188
+ ✅ Avoid conflicts and breaking changes
189
+ ✅ Coordinate changes across the codebase
190
+ ✅ Maintain consistency and quality
191
+ ✅ Save time by not rebuilding what exists
192
+
193
+ ### Contract Update Requirements
194
+
195
+ **Every contract update MUST include:**
196
+
197
+ 1. **Date stamp:** When the change was made (YYYY-MM-DD)
198
+ 2. **Version increment:** Following semver (1.0.0 → 1.0.1 or 1.1.0)
199
+ 3. **Changelog entry:** What changed and why
200
+ 4. **Impact assessment:** Breaking change? Which modules affected?
201
+ 5. **Cross-references:** Links to related contracts
202
+
203
+ **Example changelog entry:**
204
+ ```markdown
205
+ | Date | Version | Agent/Author | Changes | Impact |
206
+ |------|---------|--------------|---------|--------|
207
+ | 2024-12-02 | 1.1.0 | Coding Agent Alpha | Added user_preferences table | Non-breaking, new feature |
208
+ ```
209
+
210
+ ### Cross-Referencing Contracts
211
+
212
+ **Contracts are interconnected. Always check related contracts:**
213
+
214
+ - **DATABASE_SCHEMA_CONTRACT.md** ↔️ **SQL_CONTRACT.json**
215
+ (Tables ↔️ Queries that use them)
216
+
217
+ - **SQL_CONTRACT.json** ↔️ **API_CONTRACT.md**
218
+ (Queries ↔️ Endpoints that call them)
219
+
220
+ - **API_CONTRACT.md** ↔️ **FEATURES_CONTRACT.md**
221
+ (Endpoints ↔️ Features that use them)
222
+
223
+ - **THIRD_PARTY_INTEGRATIONS.md** ↔️ **INFRA_CONTRACT.md**
224
+ (Services ↔️ API keys/config)
225
+
226
+ - **FEATURES_CONTRACT.md** ↔️ **ALL CONTRACTS**
227
+ (Features use everything)
228
+
229
+ **When updating one contract, check if related contracts need updates too.**
230
+
231
+ ### Initial Contract Population
232
+
233
+ **If contracts are empty/incomplete, the DevOps Agent can generate them:**
234
+
235
+ See the "Initial Population Instructions" section in each contract file for:
236
+ - Search patterns to find existing code
237
+ - File locations to check
238
+ - How to extract and document information
239
+ - Automated script approaches
240
+
241
+ **DevOps Agent can execute coding agent scripts to:**
242
+ 1. Scan the entire codebase
243
+ 2. Identify all features, APIs, database tables, etc.
244
+ 3. Generate contract files automatically
245
+ 4. Iteratively improve contracts
246
+
247
+ ### Enforcement & Quality Gates
248
+
249
+ **1. Automated Validation (Coming Soon)**
250
+ We are moving towards "Executable Specifications". Soon, build scripts will validate that contracts match the codebase.
251
+ * **Drift Check:** `npm run validate-contracts` will fail if code and contracts diverge.
252
+ * **Pre-commit Hook:** Will prevent commits that violate contracts.
253
+
254
+ **2. TDD is Paramount**
255
+ **Contracts do NOT replace Test-Driven Development (TDD).**
256
+ * **Tests** are the executable specification of *behavior*.
257
+ * **Contracts** are the executable specification of *architecture/schema*.
258
+ * **Rule:** You must write tests AND update contracts. One does not substitute for the other.
259
+
260
+ **3. Manual Rejection (Temporary)**
261
+ Until automation is fully in place, the user should reject your changes if you:
262
+ - Create a feature without checking FEATURES_CONTRACT.md first
263
+ - Write SQL without checking SQL_CONTRACT.json first
264
+ - Create an API endpoint without checking API_CONTRACT.md first
265
+ - Integrate a service without checking THIRD_PARTY_INTEGRATIONS.md first
266
+ - Modify database without checking DATABASE_SCHEMA_CONTRACT.md first
267
+ - Add env vars without checking INFRA_CONTRACT.md first
268
+
269
+ **You are violating house rules and creating technical debt.**
270
+
271
+ **The user should reject your changes and require you to:**
272
+ 1. Read the relevant contract(s)
273
+ 2. Check for existing implementation
274
+ 3. Reuse or properly document your changes
275
+ 4. Update contracts appropriately
276
+
277
+ ### Quick Reference
278
+
279
+ **Before you code, ask yourself:**
280
+
281
+ - 📋 "Does this feature already exist?" → Check `FEATURES_CONTRACT.md`
282
+ - 🔌 "Does this API endpoint already exist?" → Check `API_CONTRACT.md`
283
+ - 🗄️ "Does this database table already exist?" → Check `DATABASE_SCHEMA_CONTRACT.md`
284
+ - 📝 "Does this SQL query already exist?" → Check `SQL_CONTRACT.json`
285
+ - 🌐 "Is this service already integrated?" → Check `THIRD_PARTY_INTEGRATIONS.md`
286
+ - ⚙️ "Does this env variable already exist?" → Check `INFRA_CONTRACT.md`
287
+
288
+ **If the answer is YES → REUSE IT**
289
+ **If the answer is NO → CREATE IT and DOCUMENT IT**
290
+
291
+ ---
292
+
293
+ ## Project Structure
294
+ **Current Directory Layout:**
295
+ ```
296
+ DevOpsAgent/
297
+ ├── src/ # All source code
298
+ ├── test_cases/ # All test files
299
+ ├── test_scripts/ # Test execution scripts
300
+ ├── docs/ # Documentation
301
+ ├── deploy_test/ # Deployment test scripts
302
+ ├── infrastructure/ # Infrastructure docs (READ BEFORE CREATING RESOURCES)
303
+ │ └── infrastructure.md # Server, instance, Docker information
304
+ ├── local_deploy/ # Local-only files (gitignored) - ALL DEBUG/TEMP FILES GO HERE
305
+ └── product_requirement_docs/ # PRDs
306
+ ```
307
+
308
+ ### Infrastructure Folder Requirements
309
+
310
+ The `/infrastructure/` folder contains critical system information:
311
+ - **infrastructure.md**: Documents all servers, instances, Docker containers, and their configurations
312
+ - **MUST READ** this file before creating any new infrastructure
313
+ - **MUST UPDATE** this file when you create new resources
314
+ - Include resource names, purposes, ports, dependencies, and access information
315
+
316
+ ### Important: Local-Only Files Policy
317
+
318
+ **ALL temporary, debug, and local-only files MUST be placed in `local_deploy/` folder**
319
+
320
+ This folder is gitignored and will never be uploaded to the repository. Use it for:
321
+ - Debug logs and output files
322
+ - Temporary test data
323
+ - Local configuration overrides
324
+ - Session logs and traces
325
+ - Performance profiling results
326
+ - Any files containing sensitive data
327
+ - Migration scripts for local use only
328
+ - Backup files before major changes
329
+ - **WORKTREES FOR DEVOPS AGENT'S OWN DEVELOPMENT**
330
+ - **SESSION DATA WHEN DOGFOODING THE AGENT**
331
+ - **ALL LOCKS AND COORDINATION FILES**
332
+
333
+ ### Development vs Production Usage
334
+
335
+ **When developing DevOpsAgent itself (dogfooding):**
336
+ - All worktrees go in: `local_deploy/worktrees/`
337
+ - All session locks go in: `local_deploy/session-locks/`
338
+ - All instructions go in: `local_deploy/instructions/`
339
+ - All session data go in: `local_deploy/sessions/`
340
+ - This keeps the main repo clean while we develop
341
+
342
+ **When DevOpsAgent is used on OTHER projects (production):**
343
+ - It will create `.worktrees/` in the target project
344
+ - It will create `.session-locks/` in the target project
345
+ - Those folders should be added to the target project's .gitignore
346
+
347
+ **Examples:**
348
+ ```bash
349
+ # Good - files in local_deploy/ won't be committed
350
+ local_deploy/debug.log
351
+ local_deploy/session-traces/
352
+ local_deploy/temp-test-data.json
353
+ local_deploy/performance-profile.txt
354
+ local_deploy/migration-backup/
355
+
356
+ # Bad - these would be tracked by git
357
+ ./debug.log
358
+ ./temp-data.json
359
+ ./test-output.txt
360
+ ```
361
+
362
+ ## Commit Policy
363
+
364
+ ### 1. Single Commit Message File (`.claude-commit-msg`)
365
+
366
+ **Location**: Project root `.claude-commit-msg`
367
+ **Action**: WRITE to this file (the DevOps agent will process it)
368
+ **Format**:
369
+ ```
370
+ type(scope): subject line describing the change (max 72 characters)
371
+
372
+ [WHY - 2 lines explaining the motivation/reason for these changes]
373
+ This change was needed because [specific problem or requirement].
374
+ [Additional context about why this approach was chosen].
375
+
376
+ [WHAT - Each item identifies files changed and what was done]
377
+ - File(s): path/to/file1.js, file2.js - Specific change made to these files
378
+ - File(s): src/module.js - Behavioral change or feature added
379
+ - File(s): docs/README.md, config.json - Related updates or side effects
380
+ ```
381
+
382
+ **Commit Types (REQUIRED - MUST use one of these)**:
383
+ - `feat:` - New feature or capability added
384
+ - `fix:` - Bug fix or error correction
385
+ - `refactor:` - Code restructuring without changing functionality
386
+ - `docs:` - Documentation updates (README, comments, PRDs)
387
+ - `test:` - Adding or modifying tests
388
+ - `chore:` - Maintenance tasks (configs, dependencies, cleanup)
389
+ - `style:` - Code formatting, no functional changes
390
+ - `infra:` - Infrastructure changes (servers, Docker, deployment)
391
+
392
+ **CRITICAL**: All commit messages MUST start with one of these prefixes followed by a colon.
393
+ The DevOps agent will reject commits that don't follow this format.
394
+
395
+ **Rules**:
396
+ - Always start with WHY (2 lines): Explain the problem/need that motivated these changes
397
+ - For each WHAT item: List the specific files changed, then describe what was done
398
+ - Format: "File(s): path/to/file.ext, other.ext - Description of changes"
399
+ - Group related file changes together in one bullet point
400
+ - Be specific about WHAT changed and WHERE (exact file paths)
401
+ - Describe the IMPACT of the change, not just what was done
402
+ - Never include bash commands or command-line syntax
403
+ - Never attempt to run git commands directly
404
+ - Keep the subject line under 72 characters
405
+ - Use present tense ("add" not "added", "fix" not "fixed")
406
+
407
+ ### Infrastructure Change Requirements
408
+
409
+ When making infrastructure changes, your commit MUST:
410
+ - Use `infra` type in commit message
411
+ - Update `/infrastructure/infrastructure.md` with new resources
412
+ - Document resource purpose, configuration, and dependencies
413
+ - Include rollback instructions if applicable
414
+
415
+ **Example Infrastructure Commit Message**:
416
+ ```
417
+ infra(docker): add PostgreSQL database container for user service
418
+
419
+ The user service needs a dedicated database instance with persistent storage.
420
+ This approach uses Docker Compose for easier local development and testing.
421
+
422
+ - File(s): docker-compose.yml - Add postgres service with volume and environment configuration
423
+ - File(s): infrastructure/infrastructure.md - Document new database container details and connection info
424
+ - File(s): .env.example - Add database credentials template
425
+ ```
426
+
427
+ **Example Commit Message**:
428
+ ```
429
+ fix(worktree): resolve push-behind error in multi-agent scenarios
430
+
431
+ The DevOps agent was failing when multiple agents pushed to the same branch simultaneously.
432
+ This fix adds retry logic with pull-merge to handle the common "behind remote" scenario.
433
+
434
+ - File(s): src/cs-devops-agent-worker.js - Add retry logic with git pull --no-rebase on push failures
435
+ - File(s): src/utils.js, src/git-helpers.js - Extract common git operations into reusable helper functions
436
+ - File(s): test_cases/worktree/20250929_push_behind_spec.js - Add test case for push-behind scenario
437
+ - File(s): docs/README.md - Document the new retry behavior and configuration options
438
+ ```
439
+
440
+ ### 2. Product Requirement Docs Updates
441
+
442
+ **When making code changes**: Also update relevant files in the `product_requirement_docs/` folder
443
+ - Keep PRDs in sync with implementation
444
+ - Document new features and their rationale
445
+ - Update affected system components
446
+
447
+ ## Session Recovery and Context Persistence
448
+
449
+ ### Crash Recovery System (temp_todo.md)
450
+
451
+ **Purpose**: Maintain session continuity across potential crashes or disconnections.
452
+
453
+ **Location**: `/temp_todo.md` (project root)
454
+
455
+ **When to Use**:
456
+ - Starting any multi-step task
457
+ - Before executing complex operations
458
+ - When debugging issues that may cause crashes
459
+ - Whenever working on tasks that modify multiple files
460
+
461
+ **Format**:
462
+ ```markdown
463
+ # Current Session Context
464
+ Last Updated: YYYY-MM-DDTHH:MM:SSZ
465
+
466
+ ## Task Overview
467
+ [Brief description of what the user asked for]
468
+
469
+ ## Current Status
470
+ [What step we're on, what's completed, what's pending]
471
+
472
+ ## Infrastructure Context
473
+ [Any infrastructure being created/modified]
474
+
475
+ ## Execution Plan
476
+ - [ ] Step 1: Description
477
+ - [x] Step 2: Description (completed)
478
+ - [ ] Step 3: Description (in progress)
479
+
480
+ ## Relevant Context
481
+ - Key files being modified:
482
+ - file1.js: [what changes]
483
+ - file2.sh: [what changes]
484
+ - Important findings:
485
+ - [Any discovered issues or insights]
486
+ - Dependencies/Requirements:
487
+ - [Libraries, services needed]
488
+
489
+ ## Current Working State
490
+ [Any variables, partial results, or important data to preserve]
491
+
492
+ ## Next Steps
493
+ [What should happen next if session resumes]
494
+
495
+ ## Error Log (if any)
496
+ [Any errors encountered and their resolution status]
497
+ ```
498
+
499
+ **Recovery Process**:
500
+ When starting a new session:
501
+ 1. Always check `temp_todo.md` first
502
+ 2. If it contains data, ask user: "I found a previous session context. Should I continue where we left off?"
503
+ 3. If continuing, resume from "Next Steps"
504
+ 4. If not continuing, clear the file and start fresh
505
+
506
+ ## Code Quality & Documentation Standards
507
+
508
+ ### Module/File Headers
509
+ Every JavaScript file should start with a comprehensive header:
510
+ ```javascript
511
+ /**
512
+ * ============================================================================
513
+ * MODULE NAME - Brief Description
514
+ * ============================================================================
515
+ *
516
+ * This module handles [main purpose]. It provides [key functionality].
517
+ *
518
+ * Key Components:
519
+ * - ComponentA: Does X
520
+ * - ComponentB: Handles Y
521
+ *
522
+ * Dependencies:
523
+ * - External: library1, library2
524
+ * - Internal: module.submodule
525
+ *
526
+ * Usage Example:
527
+ * const { MainClass } = require('./this_module');
528
+ * const instance = new MainClass();
529
+ * const result = instance.process();
530
+ * ============================================================================
531
+ */
532
+ ```
533
+
534
+ ### Function/Method Comments
535
+ ```javascript
536
+ /**
537
+ * Execute a named operation with the provided input.
538
+ *
539
+ * @param {string} operationName - Name of the operation to execute
540
+ * @param {Object} input - Input data for the operation
541
+ * @param {Object} [context={}] - Optional context for execution
542
+ * @returns {Promise<Object>} Result object with status and output
543
+ * @throws {Error} If operation fails or times out
544
+ *
545
+ * @example
546
+ * const result = await execute('process', { data: 'test' });
547
+ * if (result.success) {
548
+ * console.log(result.output);
549
+ * }
550
+ */
551
+ ```
552
+
553
+ ### Inline Comments
554
+ ```javascript
555
+ // Good inline comments explain WHY, not WHAT
556
+ const DEBOUNCE_MS = 3000; // Longer delay for commit messages to ensure complete writes
557
+
558
+ // Document complex logic
559
+ if (retries > 0) {
560
+ // Pull failed due to behind remote, retry with merge
561
+ // This handles the common case where another agent pushed first
562
+ execSync('git pull --no-rebase origin main');
563
+ }
564
+
565
+ // TODO/FIXME format
566
+ // TODO(username, 2025-09-29): Implement parallel worktree creation
567
+ // FIXME(username, 2025-09-29): Handle edge case when worktree already exists
568
+ ```
569
+
570
+ ## Testing Policy
571
+
572
+ ### Core Testing Principles
573
+
574
+ **Location**: Put tests under `test_cases/<area>/<component>/`
575
+ - Example: `test_cases/cs-devops-agent/worker/`
576
+ - Example: `test_cases/worktree/manager/`
577
+
578
+ **Naming Convention**:
579
+ - Files: `YYYYMMDD_<short-slug>_spec.js`
580
+ - Example: `20250929_push_behind_spec.js`
581
+
582
+ **Test Structure**:
583
+ ```javascript
584
+ /**
585
+ * Test Case: <human title>
586
+ * - Area: <domain area>
587
+ * - Component: <component/module>
588
+ * - Related Issue/PR: <#id or link>
589
+ * - Repro Summary: <1-3 lines on steps/inputs>
590
+ * - Expected Behavior: <what should happen>
591
+ * - Regression Guard: <what would break if this fails again>
592
+ */
593
+
594
+ describe('Feature Name', () => {
595
+ beforeEach(() => {
596
+ // Setup
597
+ });
598
+
599
+ it('should handle specific scenario', () => {
600
+ // Arrange - set up test data
601
+ const testData = { /* ... */ };
602
+
603
+ // Act - perform the action
604
+ const result = performAction(testData);
605
+
606
+ // Assert - verify the result
607
+ expect(result).toBe(expected);
608
+ });
609
+ });
610
+ ```
611
+
612
+ ### Test Execution Strategy
613
+
614
+ **Run specific area tests**:
615
+ ```bash
616
+ # Working on cs-devops-agent-worker.js?
617
+ npm test test_cases/cs-devops-agent/worker/
618
+
619
+ # Working on worktree management?
620
+ npm test test_cases/worktree/
621
+
622
+ # Just fixed a specific bug?
623
+ npm test test_cases/worktree/manager/20250929_detection_spec.js
624
+ ```
625
+
626
+ ### Bug Fix Test Process (MANDATORY)
627
+
628
+ 1. **Create failing test FIRST (Red phase)**
629
+ 2. **Fix the bug (Green phase)**
630
+ 3. **Run area tests (Verification)**
631
+ 4. **Run full suite only before commit**
632
+
633
+ ## Multi-Agent Coordination
634
+
635
+ ### Session Management
636
+
637
+ **Starting a new session**:
638
+ ```bash
639
+ # Interactive session starter (recommended)
640
+ npm start
641
+ # or
642
+ ./start-devops-session.sh
643
+ ```
644
+
645
+ This will:
646
+ 1. Ask if you want to use an existing session or create new
647
+ 2. Generate instructions for your coding agent
648
+ 3. Start the DevOps agent monitoring the appropriate worktree
649
+
650
+ ### Worktree Organization
651
+
652
+ **Branch Naming**:
653
+ - Agent branches: `agent/<agent-name>/<task-name>`
654
+ - Daily branches: `dev_sdd_YYYY-MM-DD`
655
+ - Session branches: `<agent>/<session-id>/<task>`
656
+
657
+ **Session Files**:
658
+ - `.devops-session.json` - Session configuration
659
+ - `.devops-commit-<session-id>.msg` - Session-specific commit message file
660
+ - `SESSION_README.md` - Session documentation
661
+
662
+ ### Multiple Coding Agent Sessions
663
+
664
+ **Each session gets**:
665
+ - Unique session ID
666
+ - Dedicated worktree
667
+ - Own commit message file
668
+ - Isolated branch
669
+
670
+ **Coordination Files**:
671
+ - `.session-locks/` - Active session locks
672
+ - `.agent-sessions.json` - Session registry
673
+ - `.worktrees/` - Agent worktrees
674
+
675
+ ## Environment Variables
676
+
677
+ ### Core CS_DevOpsAgent Settings
678
+ ```bash
679
+ AC_MSG_FILE=".claude-commit-msg" # Commit message file
680
+ AC_BRANCH_PREFIX="dev_sdd_" # Branch naming prefix
681
+ AC_PUSH=true # Auto-push after commit
682
+ AC_CLEAR_MSG_WHEN="push" # When to clear message file
683
+ AC_MSG_DEBOUNCE_MS=3000 # Wait time after message change
684
+ ```
685
+
686
+ ### Session-Specific Variables
687
+ ```bash
688
+ DEVOPS_SESSION_ID="abc-123" # Current session ID
689
+ AGENT_NAME="claude" # Agent identifier
690
+ AGENT_WORKTREE="claude-abc-123-task" # Worktree name
691
+ ```
692
+
693
+ ## File Paths and References
694
+
695
+ ### Path Formatting Rules
696
+ - Use relative paths for files in same/sub/parent directories
697
+ - Use absolute paths for system files or files outside working tree
698
+ - Examples:
699
+ - Same directory: `main.js`, `config.yaml`
700
+ - Subdirectory: `src/worker.js`, `test_cases/unit/test.js`
701
+ - Parent directory: `../package.json`, `../../Makefile`
702
+ - Absolute: `/etc/hosts`, `/usr/local/bin/node`
703
+
704
+ ### Code Block Formatting
705
+ ```javascript path=/absolute/path/to/file.js start=10
706
+ // Real code from actual file
707
+ ```
708
+
709
+ ```javascript path=null start=null
710
+ // Example or hypothetical code
711
+ ```
712
+
713
+ ## Logging Policy
714
+
715
+ ### Log File Location
716
+ **IMPORTANT: All log files MUST be written to `local_deploy/logs/` directory**
717
+
718
+ ```javascript
719
+ const LOG_DIR = './local_deploy/logs';
720
+ const LOG_FILE = `${LOG_DIR}/devops-agent-${new Date().toISOString().split('T')[0]}.log`;
721
+
722
+ // Ensure log directory exists
723
+ if (!fs.existsSync(LOG_DIR)) {
724
+ fs.mkdirSync(LOG_DIR, { recursive: true });
725
+ }
726
+ ```
727
+
728
+ ### Log Levels
729
+ ```javascript
730
+ const log = (...args) => {
731
+ const message = `[cs-devops-agent] ${args.join(' ')}`;
732
+ console.log(message);
733
+ // Also write to file in local_deploy
734
+ appendToLogFile(message);
735
+ };
736
+
737
+ const dlog = (...args) => {
738
+ if (DEBUG) {
739
+ const message = `[debug] ${args.join(' ')}`;
740
+ console.log(message);
741
+ appendToLogFile(message);
742
+ }
743
+ };
744
+
745
+ function appendToLogFile(message) {
746
+ const timestamp = new Date().toISOString();
747
+ fs.appendFileSync(LOG_FILE, `${timestamp} ${message}\n`);
748
+ }
749
+ ```
750
+
751
+ ### What to Log
752
+ - Session creation/destruction
753
+ - Worktree operations
754
+ - Git operations (commits, pushes, pulls)
755
+ - Infrastructure changes
756
+ - Error conditions and recovery attempts
757
+ - Agent coordination events
758
+
759
+ ### Log Rotation
760
+ - Keep logs in `local_deploy/logs/` organized by date
761
+ - Format: `devops-agent-YYYY-MM-DD.log`
762
+ - Never commit log files to git
763
+
764
+ ### Security - NEVER Log
765
+ - API keys or tokens
766
+ - Full file contents (use hashes or excerpts)
767
+ - User credentials
768
+ - Sensitive configuration
769
+
770
+ ## Infrastructure Management
771
+
772
+ ### Before Creating Resources
773
+
774
+ 1. **Read Current State**: Always read `/infrastructure/infrastructure.md` first
775
+ 2. **Check for Conflicts**: Ensure no port conflicts or naming collisions
776
+ 3. **Plan Integration**: Consider how new resources integrate with existing ones
777
+
778
+ ### Documentation Requirements
779
+
780
+ When creating infrastructure, document in `/infrastructure/infrastructure.md`:
781
+ - **Resource Name**: Clear, descriptive name
782
+ - **Type**: Server, container, service, etc.
783
+ - **Purpose**: What this resource does
784
+ - **Configuration**: Ports, environment variables, volumes
785
+ - **Dependencies**: What other resources it needs
786
+ - **Access Information**: How to connect or manage it
787
+ - **Rollback Plan**: How to safely remove if needed
788
+
789
+ ### Infrastructure Change Process
790
+
791
+ 1. Read `/infrastructure/infrastructure.md`
792
+ 2. Declare intent in file coordination
793
+ 3. Create/modify infrastructure
794
+ 4. Update `/infrastructure/infrastructure.md`
795
+ 5. Test the changes
796
+ 6. Commit with `infra` type
797
+
798
+ ## Common Workflows
799
+
800
+ ### 1. Starting a New Development Session
801
+ ```bash
802
+ npm start
803
+ # Select "N" for new session
804
+ # Enter task name
805
+ # Copy instructions to your coding agent
806
+ ```
807
+
808
+ ### 2. Handling Push-Behind Scenarios
809
+ The agent automatically:
810
+ 1. Detects push failures
811
+ 2. Pulls with --no-rebase to merge
812
+ 3. Retries the push
813
+ 4. Alerts on conflicts
814
+
815
+ ### 3. Multiple Agent Coordination
816
+ ```bash
817
+ # Terminal 1: Start agent for feature-auth
818
+ ./start-devops-session.sh
819
+ # Creates session abc-123
820
+
821
+ # Terminal 2: Start agent for api-endpoints
822
+ ./start-devops-session.sh
823
+ # Creates session def-456
824
+
825
+ # Each coding agent works in their respective worktree
826
+ ```
827
+
828
+ ## Review Cadence
829
+
830
+ - Review this file quarterly
831
+ - Update when adding major features
832
+ - Keep in sync with actual implementation
833
+ - Document lessons learned from production issues
834
+
835
+ ## Additional Development Guidelines
836
+
837
+ ### Error Handling
838
+
839
+ **Always provide meaningful error messages:**
840
+ ```javascript
841
+ // Bad
842
+ if (!file) throw new Error('Error');
843
+
844
+ // Good
845
+ if (!file) {
846
+ throw new Error(`File not found: ${filePath}. Ensure the file exists and you have read permissions.`);
847
+ }
848
+ ```
849
+
850
+ **Use try-catch appropriately:**
851
+ ```javascript
852
+ try {
853
+ const result = await riskyOperation();
854
+ return result;
855
+ } catch (error) {
856
+ // Log the error with context
857
+ console.error(`Failed to perform operation: ${error.message}`, {
858
+ operation: 'riskyOperation',
859
+ context: relevantContext
860
+ });
861
+
862
+ // Decide whether to recover or propagate
863
+ if (canRecover(error)) {
864
+ return fallbackValue;
865
+ }
866
+ throw error; // Re-throw if unrecoverable
867
+ }
868
+ ```
869
+
870
+ ### Code Organization
871
+
872
+ **Single Responsibility Principle:**
873
+ - Each function should do one thing well
874
+ - Each module should have a clear, focused purpose
875
+ - If a function is > 50 lines, consider breaking it down
876
+
877
+ **DRY (Don't Repeat Yourself):**
878
+ - Extract common logic into utility functions
879
+ - Use configuration objects for repeated patterns
880
+ - Create abstractions for repeated workflows
881
+
882
+ ### Performance Considerations
883
+
884
+ **File System Operations:**
885
+ ```javascript
886
+ // Use async operations for better performance
887
+ const fs = require('fs').promises;
888
+
889
+ // Good - non-blocking
890
+ const data = await fs.readFile(path, 'utf8');
891
+
892
+ // Avoid - blocking
893
+ const data = fs.readFileSync(path, 'utf8');
894
+ ```
895
+
896
+ **Git Operations:**
897
+ - Batch operations when possible
898
+ - Use `--no-pager` for git commands to avoid hanging
899
+ - Implement retry logic for network-dependent operations
900
+
901
+ ### Security Best Practices
902
+
903
+ **Input Validation:**
904
+ ```javascript
905
+ // Always validate and sanitize inputs
906
+ function processPath(userPath) {
907
+ // Prevent directory traversal
908
+ if (userPath.includes('../') || userPath.includes('..\\')) {
909
+ throw new Error('Invalid path: directory traversal detected');
910
+ }
911
+
912
+ // Ensure path is within allowed directory
913
+ const resolvedPath = path.resolve(userPath);
914
+ if (!resolvedPath.startsWith(ALLOWED_BASE_PATH)) {
915
+ throw new Error('Path outside allowed directory');
916
+ }
917
+
918
+ return resolvedPath;
919
+ }
920
+ ```
921
+
922
+ **Command Injection Prevention:**
923
+ ```javascript
924
+ // Never concatenate user input into shell commands
925
+ // Bad
926
+ execSync(`git checkout ${userBranch}`);
927
+
928
+ // Good - use array arguments
929
+ execSync('git', ['checkout', userBranch]);
930
+ ```
931
+
932
+ ### Git Workflow Best Practices
933
+
934
+ **Commit Guidelines:**
935
+ - Make atomic commits (one logical change per commit)
936
+ - Write clear, descriptive commit messages
937
+ - Reference issues/PRs when applicable
938
+ - Avoid committing commented-out code
939
+
940
+ **Branch Management:**
941
+ - Keep branches focused on single features/fixes
942
+ - Regularly sync with main branch
943
+ - Clean up merged branches
944
+ - Use meaningful branch names
945
+
946
+ ### Documentation Requirements
947
+
948
+ **README Updates:**
949
+ - Update README when adding new features
950
+ - Include usage examples for new functionality
951
+ - Document breaking changes prominently
952
+ - Keep installation instructions current
953
+
954
+ **API Documentation:**
955
+ - Document all public functions/methods
956
+ - Include parameter types and return values
957
+ - Provide usage examples
958
+ - Note any side effects or prerequisites
959
+
960
+ ### Debugging Helpers
961
+
962
+ **Debug Mode:**
963
+ ```javascript
964
+ // Use environment variable for debug output
965
+ const DEBUG = process.env.DEBUG === 'true';
966
+ const DEBUG_FILE = process.env.DEBUG_FILE || './local_deploy/debug.log';
967
+
968
+ function debugLog(...args) {
969
+ if (DEBUG) {
970
+ const timestamp = new Date().toISOString();
971
+ const message = `[DEBUG] ${timestamp} ${args.join(' ')}`;
972
+ console.log(message);
973
+
974
+ // Also write to debug file in local_deploy
975
+ if (DEBUG_FILE) {
976
+ fs.appendFileSync(DEBUG_FILE, message + '\n');
977
+ }
978
+ }
979
+ }
980
+ ```
981
+
982
+ **Debug Output Location:**
983
+ - All debug files MUST be written to `local_deploy/` directory
984
+ - Never write debug output to the project root or src directories
985
+ - Example: `local_deploy/debug-${Date.now()}.log`
986
+
987
+ **Performance Timing:**
988
+ ```javascript
989
+ function timeOperation(name, fn) {
990
+ const start = Date.now();
991
+ const result = fn();
992
+ const duration = Date.now() - start;
993
+ console.log(`[PERF] ${name} took ${duration}ms`);
994
+ return result;
995
+ }
996
+ ```
997
+
998
+ ### Dependency Management
999
+
1000
+ **Package.json Best Practices:**
1001
+ - Use exact versions for critical dependencies
1002
+ - Document why each dependency is needed
1003
+ - Regularly audit for security vulnerabilities
1004
+ - Keep dependencies up to date
1005
+
1006
+ **Import Organization:**
1007
+ ```javascript
1008
+ // Group imports logically
1009
+ // 1. Node built-ins
1010
+ import fs from 'fs';
1011
+ import path from 'path';
1012
+
1013
+ // 2. External dependencies
1014
+ import express from 'express';
1015
+ import lodash from 'lodash';
1016
+
1017
+ // 3. Internal modules
1018
+ import { config } from './config';
1019
+ import { utils } from './utils';
1020
+ ```
1021
+
1022
+ ### Code Review Checklist
1023
+
1024
+ Before committing, verify:
1025
+ - [ ] Tests pass
1026
+ - [ ] No console.log() left in production code
1027
+ - [ ] Error handling is comprehensive
1028
+ - [ ] Documentation is updated
1029
+ - [ ] Code follows project style guide
1030
+ - [ ] No sensitive data in code or comments
1031
+ - [ ] Performance impact considered
1032
+ - [ ] Security implications reviewed
1033
+
1034
+ ### Communication with Users
1035
+
1036
+ **Progress Updates:**
1037
+ - Provide clear status updates for long-running operations
1038
+ - Use spinners or progress bars where appropriate
1039
+ - Estimate completion time when possible
1040
+
1041
+ **Error Communication:**
1042
+ - Explain what went wrong in user-friendly terms
1043
+ - Suggest potential fixes or workarounds
1044
+ - Provide links to documentation when relevant
1045
+ - Include error codes for support reference
1046
+
1047
+
1048
+ ---
1049
+
1050
+ ## 🤖 DevOps Agent Automation (NEW: 2024-12-02)
1051
+
1052
+ **The DevOps Agent can now automatically generate, validate, and maintain contract files.**
1053
+
1054
+ ### Automation Scripts
1055
+
1056
+ All automation scripts are located in `scripts/contract-automation/`:
1057
+
1058
+ 1. **generate-contracts.js** - Scan codebase and extract contract information
1059
+ 2. **analyze-with-llm.js** - Use Groq LLM for intelligent analysis
1060
+ 3. **validate-commit.js** - Validate commit messages with contract flags
1061
+ 4. **check-compliance.js** - Check if contracts are in sync with code
1062
+
1063
+ See `scripts/contract-automation/README.md` for detailed documentation.
1064
+
1065
+ ### Contract Generation Workflow
1066
+
1067
+ **Step 1: Local Scanning**
1068
+
1069
+ ```bash
1070
+ node scripts/contract-automation/generate-contracts.js --verbose
1071
+ ```
1072
+
1073
+ This scans the codebase and extracts:
1074
+ - Features from `src/features/` and `src/modules/`
1075
+ - API endpoints from route files
1076
+ - Database tables from migrations
1077
+ - SQL queries from code
1078
+ - Third-party integrations from package.json
1079
+ - Environment variables from code
1080
+
1081
+ Output: `House_Rules_Contracts/contract-scan-results.json`
1082
+
1083
+ **Step 2: LLM Analysis (Optional but Recommended)**
1084
+
1085
+ ```bash
1086
+ node scripts/contract-automation/analyze-with-llm.js \
1087
+ --scan-results=House_Rules_Contracts/contract-scan-results.json
1088
+ ```
1089
+
1090
+ This uses Groq LLM to:
1091
+ - Generate human-readable descriptions
1092
+ - Create user stories and acceptance criteria
1093
+ - Infer API request/response formats
1094
+ - Provide security and performance recommendations
1095
+ - Validate contract completeness
1096
+
1097
+ Output: `House_Rules_Contracts/llm-analysis-results.json`
1098
+
1099
+ **Step 3: Manual Population**
1100
+
1101
+ Review the generated JSON files and manually populate the contract markdown files with the discovered information. Use the templates already in place.
1102
+
1103
+ ### Commit Message Contract Flags (MANDATORY)
1104
+
1105
+ **All commits MUST include contract flags in this format:**
1106
+
1107
+ ```
1108
+ feat(api): add user profile endpoint
1109
+
1110
+ Contracts: [SQL:T, API:T, DB:F, 3RD:F, FEAT:T, INFRA:F]
1111
+
1112
+ [WHY] Users need to view and update their profile information.
1113
+
1114
+ [WHAT]
1115
+ - File(s): src/api/profile.js - Added GET /api/v1/profile endpoint
1116
+ - File(s): House_Rules_Contracts/API_CONTRACT.md - Documented new endpoint
1117
+ ```
1118
+
1119
+ **Contract Flags:**
1120
+ - `SQL:T/F` - SQL_CONTRACT.json modified
1121
+ - `API:T/F` - API_CONTRACT.md modified
1122
+ - `DB:T/F` - DATABASE_SCHEMA_CONTRACT.md modified
1123
+ - `3RD:T/F` - THIRD_PARTY_INTEGRATIONS.md modified
1124
+ - `FEAT:T/F` - FEATURES_CONTRACT.md modified
1125
+ - `INFRA:T/F` - INFRA_CONTRACT.md modified
1126
+
1127
+ **Validation:**
1128
+
1129
+ Before committing, run:
1130
+
1131
+ ```bash
1132
+ node scripts/contract-automation/validate-commit.js --check-staged --auto-fix
1133
+ ```
1134
+
1135
+ This will:
1136
+ - ✅ Check if claimed contract flags match actual file changes
1137
+ - ✅ Detect false positives (claimed T but not modified)
1138
+ - ✅ Detect false negatives (modified but not claimed)
1139
+ - ✅ Generate corrected commit message if --auto-fix used
1140
+
1141
+ **The DevOps Agent will alert the user if:**
1142
+ - Contract flags are missing
1143
+ - Contract flags don't match actual changes
1144
+ - Contract files should have been updated but weren't
1145
+
1146
+ ### Compliance Checking
1147
+
1148
+ **Run periodic compliance checks:**
1149
+
1150
+ ```bash
1151
+ node scripts/contract-automation/check-compliance.js
1152
+ ```
1153
+
1154
+ This checks if:
1155
+ - Features in code are documented in FEATURES_CONTRACT.md
1156
+ - API endpoints in code are documented in API_CONTRACT.md
1157
+ - Database tables in migrations are documented in DATABASE_SCHEMA_CONTRACT.md
1158
+ - Third-party services in package.json are documented in THIRD_PARTY_INTEGRATIONS.md
1159
+ - Environment variables in code are documented in INFRA_CONTRACT.md
1160
+
1161
+ **Output:**
1162
+ - List of items in code but missing from contracts
1163
+ - List of items in contracts but missing from code
1164
+ - Compliance status (pass/fail)
1165
+
1166
+ **Strict mode for CI/CD:**
1167
+
1168
+ ```bash
1169
+ node scripts/contract-automation/check-compliance.js --strict
1170
+ ```
1171
+
1172
+ Exits with error code 1 if any discrepancies found.
1173
+
1174
+ ### DevOps Agent Responsibilities
1175
+
1176
+ **The DevOps Agent MUST:**
1177
+
1178
+ 1. **Generate contracts** when setting up a new project or after major changes
1179
+ 2. **Validate commit messages** before allowing commits
1180
+ 3. **Alert users** if contract flags don't match actual changes
1181
+ 4. **Run compliance checks** periodically (weekly recommended)
1182
+ 5. **Report discrepancies** between code and contracts
1183
+ 6. **Suggest fixes** when validation fails
1184
+
1185
+ **The DevOps Agent CAN:**
1186
+
1187
+ 1. **Execute local scanning** without LLM for fast discovery
1188
+ 2. **Use Groq LLM** for intelligent analysis and recommendations
1189
+ 3. **Auto-fix commit messages** with correct contract flags
1190
+ 4. **Generate JSON reports** for programmatic processing
1191
+ 5. **Integrate with CI/CD** pipelines for automated validation
1192
+
1193
+ ### LLM Integration (Groq)
1194
+
1195
+ **The DevOps Agent can use Groq LLM via OpenAI-compatible API:**
1196
+
1197
+ **Available Models:**
1198
+ - `llama-3.1-70b-versatile` (default) - Best for complex analysis
1199
+ - `llama-3.1-8b-instant` - Faster, good for simple tasks
1200
+ - `mixtral-8x7b-32768` - Alternative with large context window
1201
+ - `gemini-2.5-flash` - Fast and efficient
1202
+
1203
+ **Environment Variable:**
1204
+ - `OPENAI_API_KEY` - Set to Groq API key (already configured in sandbox)
1205
+
1206
+ **Use Cases:**
1207
+ - Analyze code files and extract documentation
1208
+ - Generate feature descriptions and user stories
1209
+ - Infer API request/response formats
1210
+ - Validate contract completeness
1211
+ - Provide security and performance recommendations
1212
+
1213
+ **Cost Optimization:**
1214
+ - Use local scanning first (free, fast)
1215
+ - Use LLM only for enhancement and validation
1216
+ - Cache LLM results to avoid redundant calls
1217
+
1218
+ ### Hybrid Approach (Recommended)
1219
+
1220
+ **Combine local scanning + LLM analysis for best results:**
1221
+
1222
+ 1. **Local scanning** (fast, deterministic)
1223
+ - Extract structured data (tables, endpoints, queries)
1224
+ - Pattern matching and regex
1225
+ - File system operations
1226
+
1227
+ 2. **LLM analysis** (intelligent, contextual)
1228
+ - Generate human-readable descriptions
1229
+ - Infer relationships and dependencies
1230
+ - Provide recommendations
1231
+ - Validate completeness
1232
+
1233
+ 3. **Manual review** (human oversight)
1234
+ - Review generated content
1235
+ - Fill in gaps
1236
+ - Verify accuracy
1237
+ - Make final decisions
1238
+
1239
+ ### CI/CD Integration Example
1240
+
1241
+ ```yaml
1242
+ # .github/workflows/contract-validation.yml
1243
+ name: Contract Validation
1244
+
1245
+ on: [pull_request]
1246
+
1247
+ jobs:
1248
+ validate:
1249
+ runs-on: ubuntu-latest
1250
+ steps:
1251
+ - uses: actions/checkout@v2
1252
+ - uses: actions/setup-node@v2
1253
+
1254
+ - name: Install Dependencies
1255
+ run: npm install
1256
+
1257
+ - name: Check Contract Compliance
1258
+ run: node scripts/contract-automation/check-compliance.js --strict --report=json
1259
+
1260
+ - name: Validate Commit Message
1261
+ run: |
1262
+ git log -1 --pretty=%B > commit-msg.txt
1263
+ node scripts/contract-automation/validate-commit.js --commit-msg=commit-msg.txt --check-staged
1264
+ ```
1265
+
1266
+ ### Troubleshooting
1267
+
1268
+ **Issue: "Contract directory not found"**
1269
+
1270
+ Solution: Merge the contract system branch first:
1271
+ ```bash
1272
+ git merge origin/0212_SDD_Manus_HouseFilesUpgrade
1273
+ ```
1274
+
1275
+ **Issue: "OPENAI_API_KEY not set"**
1276
+
1277
+ Solution: Already set in sandbox environment. For local development:
1278
+ ```bash
1279
+ export OPENAI_API_KEY="your-groq-api-key"
1280
+ ```
1281
+
1282
+ **Issue: "No files found"**
1283
+
1284
+ Solution: Run from repository root:
1285
+ ```bash
1286
+ cd /path/to/CS_DevOpsAgent
1287
+ node scripts/contract-automation/generate-contracts.js
1288
+ ```
1289
+
1290
+ ### Best Practices
1291
+
1292
+ 1. **Run contract generation** after major feature additions
1293
+ 2. **Validate commits** before pushing to prevent issues
1294
+ 3. **Check compliance weekly** to keep contracts up-to-date
1295
+ 4. **Use LLM sparingly** to minimize API costs
1296
+ 5. **Review auto-generated content** before committing
1297
+ 6. **Document exceptions** when automation can't handle something
1298
+ 7. **Keep scripts updated** as codebase evolves
1299
+
1300
+ ### Future Enhancements
1301
+
1302
+ **Planned features:**
1303
+ - Auto-fix for compliance issues
1304
+ - Visual HTML reports with charts
1305
+ - Git hooks for pre-commit validation
1306
+ - VSCode extension for real-time validation
1307
+ - Contract versioning and diff tool
1308
+ - Dependency graph visualization
1309
+ - Dashboard for contract status
1310
+
1311
+ ---
1312
+
1313
+ **Last Updated:** 2024-12-02
1314
+ **Status:** ✅ Ready for use
1315
+
1316
+
1317
+ ---
1318
+
1319
+ ## 📋 DevOps Agent Change Workflow (NEW: 2024-12-16)
1320
+
1321
+ **This section provides a step-by-step workflow for DevOps Agents to handle change requests while adhering to the House Rules Contract System.**
1322
+
1323
+ ### Objective
1324
+
1325
+ Implement changes to the codebase while strictly adhering to the House Rules Contract System to prevent conflicts and ensure consistency across all development activities.
1326
+
1327
+ ### Context
1328
+
1329
+ As a DevOps Agent, you are responsible for maintaining the integrity of the microservices architecture. Before writing any code, you MUST follow the contract system to ensure coordination with other agents and prevent duplicate work.
1330
+
1331
+ ### Step-by-Step Change Process
1332
+
1333
+ See the comprehensive workflow documentation in `House_Rules_Contracts/README.md` for detailed examples including:
1334
+
1335
+ - How to understand change requests
1336
+ - How to consult contracts before coding
1337
+ - How to analyze and decide whether to reuse or create
1338
+ - How to implement changes following contracts
1339
+ - How to update contracts after changes
1340
+ - How to commit with proper contract flags
1341
+
1342
+ ### Quick Reference
1343
+
1344
+ **Before you code, ask yourself:**
1345
+
1346
+ - 📋 "Does this feature already exist?" → Check `FEATURES_CONTRACT.md`
1347
+ - 🔌 "Does this API endpoint already exist?" → Check `API_CONTRACT.md`
1348
+ - 🗄️ "Does this database table already exist?" → Check `DATABASE_SCHEMA_CONTRACT.md`
1349
+ - 📝 "Does this SQL query already exist?" → Check `SQL_CONTRACT.json`
1350
+ - 🌐 "Is this service already integrated?" → Check `THIRD_PARTY_INTEGRATIONS.md`
1351
+ - ⚙️ "Does this env variable already exist?" → Check `INFRA_CONTRACT.md`
1352
+
1353
+ **If YES → REUSE IT**
1354
+ **If NO → CREATE IT and DOCUMENT IT**
1355
+
1356
+ ### Mandatory Commit Format
1357
+
1358
+ ```
1359
+ <type>(<scope>): <subject>
1360
+
1361
+ Contracts: [SQL:T/F, API:T/F, DB:T/F, 3RD:T/F, FEAT:T/F, INFRA:T/F]
1362
+
1363
+ [WHY]
1364
+ <explanation of motivation>
1365
+
1366
+ [WHAT]
1367
+ - File(s): <path> - <description>
1368
+ - File(s): <path> - <description>
1369
+
1370
+ Resolves: [Task ID or Issue Number]
1371
+ Part of: House Rules Contract System
1372
+ ```
1373
+
1374
+ ### Validation Before Commit
1375
+
1376
+ ```bash
1377
+ # Validate commit message and contract flags
1378
+ node scripts/contract-automation/validate-commit.js --check-staged --auto-fix
1379
+
1380
+ # If validation passes, commit and push
1381
+ git commit -F .claude-commit-msg
1382
+ git push origin <branch-name>
1383
+ ```
1384
+
1385
+ ### Critical Reminders
1386
+
1387
+ **DO:**
1388
+
1389
+ ✅ Always check contracts BEFORE coding
1390
+ ✅ Reuse existing components when possible
1391
+ ✅ Document ALL changes in contracts immediately
1392
+ ✅ Use the mandatory commit message format
1393
+ ✅ Validate commits before pushing
1394
+ ✅ Increment version numbers appropriately
1395
+ ✅ Add comprehensive changelog entries
1396
+ ✅ Cross-reference related contracts
1397
+
1398
+ **DON'T:**
1399
+
1400
+ ❌ Create duplicate features/APIs/queries
1401
+ ❌ Skip contract consultation
1402
+ ❌ Forget to update contracts after coding
1403
+ ❌ Use incorrect commit message format
1404
+ ❌ Push without validation
1405
+ ❌ Make breaking changes without documentation
1406
+ ❌ Ignore existing implementations
1407
+ ❌ Work in isolation from other agents
1408
+
1409
+ ---
1410
+
1411
+ **Last Updated:** 2024-12-16
1412
+ **Status:** ✅ Ready for use