@webpieces/code-rules 0.0.1

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.
@@ -0,0 +1,812 @@
1
+ /**
2
+ * Validate Modified Methods Executor
3
+ *
4
+ * Validates that modified methods don't exceed a maximum line count (default 80).
5
+ * This encourages gradual cleanup of legacy long methods - when you touch a method,
6
+ * you must bring it under the limit.
7
+ *
8
+ * Combined with validate-new-methods, this creates a gradual
9
+ * transition to cleaner code:
10
+ * - New methods: must be under limit
11
+ * - Modified methods: must be under limit (cleanup when touched)
12
+ * - Untouched methods: no limit (legacy allowed)
13
+ *
14
+ * Usage:
15
+ * nx affected --target=validate-modified-methods --base=origin/main
16
+ *
17
+ * Escape hatch: Add webpieces-disable max-lines-modified comment with date and justification
18
+ * Format: // webpieces-disable max-lines-modified 2025/01/15 -- [reason]
19
+ * The disable expires after 1 month from the date specified.
20
+ */
21
+
22
+ import { execSync } from 'child_process';
23
+ import * as fs from 'fs';
24
+ import * as path from 'path';
25
+ import * as ts from 'typescript';
26
+
27
+ export type MethodMaxLimitMode = 'OFF' | 'NEW_METHODS' | 'NEW_AND_MODIFIED_METHODS' | 'MODIFIED_FILES';
28
+
29
+ export interface ValidateModifiedMethodsOptions {
30
+ limit?: number;
31
+ mode?: MethodMaxLimitMode;
32
+ disableAllowed?: boolean;
33
+ }
34
+
35
+ export interface ExecutorResult {
36
+ success: boolean;
37
+ }
38
+
39
+ interface MethodViolation {
40
+ file: string;
41
+ methodName: string;
42
+ line: number;
43
+ lines: number;
44
+ expiredDisable?: boolean;
45
+ expiredDate?: string;
46
+ }
47
+
48
+ const TMP_DIR = '.webpieces/instruct-ai';
49
+ const TMP_MD_FILE = 'webpieces.methodsize.md';
50
+
51
+ const METHODSIZE_DOC_CONTENT = `# Instructions: Method Too Long
52
+
53
+ ## Requirement
54
+
55
+ **~99% of the time**, you can stay under the \`limit\` from nx.json
56
+ by extracting logical units into well-named methods.
57
+ Nearly all software can be written with methods under this size.
58
+ Take the extra time to refactor - it's worth it for long-term maintainability.
59
+
60
+ ## The "Table of Contents" Principle
61
+
62
+ Good code reads like a book's table of contents:
63
+ - Chapter titles (method names) tell you WHAT happens
64
+ - Reading chapter titles gives you the full story
65
+ - You can dive into chapters (implementations) for details
66
+
67
+ ## Why Limit Method Sizes?
68
+
69
+ Methods under reasonable limits are:
70
+ - Easy to review in a single screen
71
+ - Simple to understand without scrolling
72
+ - Quick for AI to analyze and suggest improvements
73
+ - More testable in isolation
74
+ - Self-documenting through well-named extracted methods
75
+
76
+ ## Gradual Cleanup Strategy
77
+
78
+ This codebase uses a gradual cleanup approach:
79
+ - **New methods**: Must be under \`limit\` from nx.json
80
+ - **Modified methods**: Must be under \`limit\` from nx.json
81
+ - **Untouched methods**: No limit (legacy code is allowed until touched)
82
+
83
+ ## How to Refactor
84
+
85
+ Instead of:
86
+ \`\`\`typescript
87
+ async processOrder(order: Order): Promise<Result> {
88
+ // 100 lines of validation, transformation, saving, notifications...
89
+ }
90
+ \`\`\`
91
+
92
+ Write:
93
+ \`\`\`typescript
94
+ async processOrder(order: Order): Promise<Result> {
95
+ const validated = this.validateOrder(order);
96
+ const transformed = this.applyBusinessRules(validated);
97
+ const saved = await this.saveToDatabase(transformed);
98
+ await this.notifyStakeholders(saved);
99
+ return this.buildResult(saved);
100
+ }
101
+ \`\`\`
102
+
103
+ Now the main method is a "table of contents" - each line tells part of the story!
104
+
105
+ ## Patterns for Extraction
106
+
107
+ ### Pattern 1: Extract Loop Bodies
108
+ \`\`\`typescript
109
+ // BEFORE
110
+ for (const item of items) {
111
+ // 20 lines of processing
112
+ }
113
+
114
+ // AFTER
115
+ for (const item of items) {
116
+ this.processItem(item);
117
+ }
118
+ \`\`\`
119
+
120
+ ### Pattern 2: Extract Conditional Blocks
121
+ \`\`\`typescript
122
+ // BEFORE
123
+ if (isAdmin(user)) {
124
+ // 15 lines of admin logic
125
+ }
126
+
127
+ // AFTER
128
+ if (isAdmin(user)) {
129
+ this.handleAdminUser(user);
130
+ }
131
+ \`\`\`
132
+
133
+ ### Pattern 3: Extract Data Transformations
134
+ \`\`\`typescript
135
+ // BEFORE
136
+ const result = {
137
+ // 10+ lines of object construction
138
+ };
139
+
140
+ // AFTER
141
+ const result = this.buildResultObject(data);
142
+ \`\`\`
143
+
144
+ ## If Refactoring Is Not Feasible
145
+
146
+ Sometimes methods genuinely need to be longer (complex algorithms, state machines, etc.).
147
+
148
+ **Escape hatch**: Add a webpieces-disable comment with DATE and justification:
149
+
150
+ \`\`\`typescript
151
+ // webpieces-disable max-lines-modified 2025/01/15 -- Complex state machine, splitting reduces clarity
152
+ async complexStateMachine(): Promise<void> {
153
+ // ... longer method with justification
154
+ }
155
+ \`\`\`
156
+
157
+ **IMPORTANT**: The date format is yyyy/mm/dd. The disable will EXPIRE after 1 month from this date.
158
+ After expiration, you must either fix the method or update the date to get another month.
159
+ This ensures that disable comments are reviewed periodically.
160
+
161
+ ## AI Agent Action Steps
162
+
163
+ 1. **READ** the method to understand its logical sections
164
+ 2. **IDENTIFY** logical units that can be extracted
165
+ 3. **EXTRACT** into well-named private methods
166
+ 4. **VERIFY** the main method now reads like a table of contents
167
+ 5. **IF NOT FEASIBLE**: Add webpieces-disable max-lines-modified comment with clear justification
168
+
169
+ ## Remember
170
+
171
+ - Every method you write today will be read many times tomorrow
172
+ - The best code explains itself through structure
173
+ - When in doubt, extract and name it
174
+ `;
175
+
176
+ /**
177
+ * Write the instructions documentation to tmp directory
178
+ */
179
+ function writeTmpInstructions(workspaceRoot: string): string {
180
+ const tmpDir = path.join(workspaceRoot, TMP_DIR);
181
+ const mdPath = path.join(tmpDir, TMP_MD_FILE);
182
+
183
+ fs.mkdirSync(tmpDir, { recursive: true });
184
+ fs.writeFileSync(mdPath, METHODSIZE_DOC_CONTENT);
185
+
186
+ return mdPath;
187
+ }
188
+
189
+ /**
190
+ * Get changed TypeScript files between base and head (or working tree if head not specified).
191
+ * Uses `git diff base [head]` to match what `nx affected` does.
192
+ * When head is NOT specified, also includes untracked files (matching nx affected behavior).
193
+ */
194
+ function getChangedTypeScriptFiles(workspaceRoot: string, base: string, head?: string): string[] {
195
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
196
+ try {
197
+ // If head is specified, diff base to head; otherwise diff base to working tree
198
+ const diffTarget = head ? `${base} ${head}` : base;
199
+ const output = execSync(`git diff --name-only ${diffTarget} -- '*.ts' '*.tsx'`, {
200
+ cwd: workspaceRoot,
201
+ encoding: 'utf-8',
202
+ });
203
+ const changedFiles = output
204
+ .trim()
205
+ .split('\n')
206
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
207
+
208
+ // When comparing to working tree (no head specified), also include untracked files
209
+ // This matches what nx affected does: "All modified files not yet committed or tracked will also be added"
210
+ if (!head) {
211
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
212
+ try {
213
+ const untrackedOutput = execSync(`git ls-files --others --exclude-standard '*.ts' '*.tsx'`, {
214
+ cwd: workspaceRoot,
215
+ encoding: 'utf-8',
216
+ });
217
+ const untrackedFiles = untrackedOutput
218
+ .trim()
219
+ .split('\n')
220
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
221
+ // Merge and dedupe
222
+ const allFiles = new Set([...changedFiles, ...untrackedFiles]);
223
+ return Array.from(allFiles);
224
+ } catch (err: unknown) {
225
+ //const error = toError(err);
226
+ // If ls-files fails, just return the changed files
227
+ return changedFiles;
228
+ }
229
+ }
230
+
231
+ return changedFiles;
232
+ } catch (err: unknown) {
233
+ //const error = toError(err);
234
+ return [];
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Get the diff content for a specific file between base and head (or working tree if head not specified).
240
+ * Uses `git diff base [head]` to match what `nx affected` does.
241
+ * For untracked files, returns the entire file content as additions.
242
+ */
243
+ function getFileDiff(workspaceRoot: string, file: string, base: string, head?: string): string {
244
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
245
+ try {
246
+ // If head is specified, diff base to head; otherwise diff base to working tree
247
+ const diffTarget = head ? `${base} ${head}` : base;
248
+ const diff = execSync(`git diff ${diffTarget} -- "${file}"`, {
249
+ cwd: workspaceRoot,
250
+ encoding: 'utf-8',
251
+ });
252
+
253
+ // If diff is empty and we're comparing to working tree, check if it's an untracked file
254
+ if (!diff && !head) {
255
+ const fullPath = path.join(workspaceRoot, file);
256
+ if (fs.existsSync(fullPath)) {
257
+ // Check if file is untracked
258
+ const isUntracked = execSync(`git ls-files --others --exclude-standard "${file}"`, {
259
+ cwd: workspaceRoot,
260
+ encoding: 'utf-8',
261
+ }).trim();
262
+
263
+ if (isUntracked) {
264
+ // For untracked files, treat entire content as additions
265
+ const content = fs.readFileSync(fullPath, 'utf-8');
266
+ const lines = content.split('\n');
267
+ // Create a pseudo-diff where all lines are additions
268
+ return lines.map((line) => `+${line}`).join('\n');
269
+ }
270
+ }
271
+ }
272
+
273
+ return diff;
274
+ } catch (err: unknown) {
275
+ //const error = toError(err);
276
+ return '';
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Parse diff to find NEW method signatures.
282
+ * Must handle: export function, async function, const/let arrow functions, class methods
283
+ */
284
+ // webpieces-disable max-lines-new-methods -- Regex patterns require inline documentation
285
+ function findNewMethodSignaturesInDiff(diffContent: string): Set<string> {
286
+ const newMethods = new Set<string>();
287
+ const lines = diffContent.split('\n');
288
+
289
+ // Patterns to match method definitions (same as validate-new-methods)
290
+ const patterns = [
291
+ // [export] [async] function methodName( - most explicit, check first
292
+ /^\+\s*(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*\(/,
293
+ // [export] const/let methodName = [async] (
294
+ /^\+\s*(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/,
295
+ // [export] const/let methodName = [async] function
296
+ /^\+\s*(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?function/,
297
+ // class method: [public/private/protected] [static] [async] methodName( - but NOT constructor, if, for, while, etc.
298
+ /^\+\s*(?:(?:public|private|protected)\s+)?(?:static\s+)?(?:async\s+)?(\w+)\s*\(/,
299
+ ];
300
+
301
+ for (const line of lines) {
302
+ if (line.startsWith('+') && !line.startsWith('+++')) {
303
+ for (const pattern of patterns) {
304
+ const match = line.match(pattern);
305
+ if (match) {
306
+ // Extract method name - now always in capture group 1
307
+ const methodName = match[1];
308
+ if (methodName && !['if', 'for', 'while', 'switch', 'catch', 'constructor'].includes(methodName)) {
309
+ newMethods.add(methodName);
310
+ }
311
+ break;
312
+ }
313
+ }
314
+ }
315
+ }
316
+
317
+ return newMethods;
318
+ }
319
+
320
+ /**
321
+ * Parse diff to find line numbers that have changes in the new file
322
+ */
323
+ function getChangedLineNumbers(diffContent: string): Set<number> {
324
+ const changedLines = new Set<number>();
325
+ const lines = diffContent.split('\n');
326
+
327
+ let currentNewLine = 0;
328
+
329
+ for (const line of lines) {
330
+ // Parse hunk header: @@ -oldStart,oldCount +newStart,newCount @@
331
+ const hunkMatch = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
332
+ if (hunkMatch) {
333
+ currentNewLine = parseInt(hunkMatch[1], 10);
334
+ continue;
335
+ }
336
+
337
+ if (currentNewLine === 0) continue;
338
+
339
+ if (line.startsWith('+') && !line.startsWith('+++')) {
340
+ // Added line
341
+ changedLines.add(currentNewLine);
342
+ currentNewLine++;
343
+ } else if (line.startsWith('-') && !line.startsWith('---')) {
344
+ // Removed line - doesn't increment new line counter
345
+ } else if (!line.startsWith('\\')) {
346
+ // Context line (unchanged)
347
+ currentNewLine++;
348
+ }
349
+ }
350
+
351
+ return changedLines;
352
+ }
353
+
354
+ /**
355
+ * Parse a date string in yyyy/mm/dd format and return a Date object.
356
+ * Returns null if the format is invalid.
357
+ */
358
+ function parseDisableDate(dateStr: string): Date | null {
359
+ // Match yyyy/mm/dd format
360
+ const match = dateStr.match(/^(\d{4})\/(\d{2})\/(\d{2})$/);
361
+ if (!match) return null;
362
+
363
+ const year = parseInt(match[1], 10);
364
+ const month = parseInt(match[2], 10) - 1; // JS months are 0-indexed
365
+ const day = parseInt(match[3], 10);
366
+
367
+ const date = new Date(year, month, day);
368
+
369
+ // Validate the date is valid (e.g., not Feb 30)
370
+ if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
371
+ return null;
372
+ }
373
+
374
+ return date;
375
+ }
376
+
377
+ /**
378
+ * Check if a date is within the last month (not expired).
379
+ */
380
+ function isDateWithinMonth(date: Date): boolean {
381
+ const now = new Date();
382
+ const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
383
+ return date >= oneMonthAgo;
384
+ }
385
+
386
+ /**
387
+ * Get today's date in yyyy/mm/dd format for error messages
388
+ */
389
+ function getTodayDateString(): string {
390
+ const now = new Date();
391
+ const year = now.getFullYear();
392
+ const month = String(now.getMonth() + 1).padStart(2, '0');
393
+ const day = String(now.getDate()).padStart(2, '0');
394
+ return `${year}/${month}/${day}`;
395
+ }
396
+
397
+ interface DisableInfo {
398
+ type: 'full' | 'new-only' | 'none';
399
+ isExpired: boolean;
400
+ date?: string;
401
+ }
402
+
403
+ /**
404
+ * Check what kind of webpieces-disable comment is present for a method.
405
+ * Returns: DisableInfo with type, expiration status, and date
406
+ * - 'full': max-lines-modified (ultimate escape, skips both validators)
407
+ * - 'new-only': max-lines-new-methods (escaped 30-line check, still needs 80-line check)
408
+ * - 'none': no escape hatch
409
+ */
410
+ // webpieces-disable max-lines-new-methods -- Complex validation logic with multiple escape hatch types
411
+ function getDisableInfo(lines: string[], lineNumber: number): DisableInfo {
412
+ const startCheck = Math.max(0, lineNumber - 5);
413
+ for (let i = lineNumber - 2; i >= startCheck; i--) {
414
+ const line = lines[i]?.trim() ?? '';
415
+ if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {
416
+ break;
417
+ }
418
+ if (line.includes('webpieces-disable')) {
419
+ if (line.includes('max-lines-modified')) {
420
+ // Check for date in format: max-lines-modified yyyy/mm/dd
421
+ const dateMatch = line.match(/max-lines-modified\s+(\d{4}\/\d{2}\/\d{2}|XXXX\/XX\/XX)/);
422
+
423
+ if (!dateMatch) {
424
+ // No date found - treat as expired (invalid)
425
+ return { type: 'full', isExpired: true, date: undefined };
426
+ }
427
+
428
+ const dateStr = dateMatch[1];
429
+
430
+ // Secret permanent disable
431
+ if (dateStr === 'XXXX/XX/XX') {
432
+ return { type: 'full', isExpired: false, date: dateStr };
433
+ }
434
+
435
+ const date = parseDisableDate(dateStr);
436
+ if (!date) {
437
+ // Invalid date format - treat as expired
438
+ return { type: 'full', isExpired: true, date: dateStr };
439
+ }
440
+
441
+ if (!isDateWithinMonth(date)) {
442
+ // Date is expired (older than 1 month)
443
+ return { type: 'full', isExpired: true, date: dateStr };
444
+ }
445
+
446
+ // Valid and not expired
447
+ return { type: 'full', isExpired: false, date: dateStr };
448
+ }
449
+ if (line.includes('max-lines-new-methods')) {
450
+ // Check for date in format: max-lines-new-methods yyyy/mm/dd
451
+ const dateMatch = line.match(/max-lines-new-methods\s+(\d{4}\/\d{2}\/\d{2}|XXXX\/XX\/XX)/);
452
+
453
+ if (!dateMatch) {
454
+ // No date found - treat as expired (invalid)
455
+ return { type: 'new-only', isExpired: true, date: undefined };
456
+ }
457
+
458
+ const dateStr = dateMatch[1];
459
+
460
+ // Secret permanent disable
461
+ if (dateStr === 'XXXX/XX/XX') {
462
+ return { type: 'new-only', isExpired: false, date: dateStr };
463
+ }
464
+
465
+ const date = parseDisableDate(dateStr);
466
+ if (!date) {
467
+ // Invalid date format - treat as expired
468
+ return { type: 'new-only', isExpired: true, date: dateStr };
469
+ }
470
+
471
+ if (!isDateWithinMonth(date)) {
472
+ // Date is expired (older than 1 month)
473
+ return { type: 'new-only', isExpired: true, date: dateStr };
474
+ }
475
+
476
+ // Valid and not expired
477
+ return { type: 'new-only', isExpired: false, date: dateStr };
478
+ }
479
+ }
480
+ }
481
+ return { type: 'none', isExpired: false };
482
+ }
483
+
484
+ interface MethodInfo {
485
+ name: string;
486
+ line: number;
487
+ endLine: number;
488
+ lines: number;
489
+ disableInfo: DisableInfo;
490
+ }
491
+
492
+ /**
493
+ * Parse a TypeScript file and find methods with their line counts
494
+ */
495
+ // webpieces-disable max-lines-new-methods -- AST traversal requires inline visitor function
496
+ function findMethodsInFile(filePath: string, workspaceRoot: string): MethodInfo[] {
497
+ const fullPath = path.join(workspaceRoot, filePath);
498
+ if (!fs.existsSync(fullPath)) return [];
499
+
500
+ const content = fs.readFileSync(fullPath, 'utf-8');
501
+ const fileLines = content.split('\n');
502
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
503
+
504
+ const methods: MethodInfo[] = [];
505
+
506
+ // webpieces-disable max-lines-new-methods -- AST visitor pattern requires handling multiple node types
507
+ function visit(node: ts.Node): void {
508
+ let methodName: string | undefined;
509
+ let startLine: number | undefined;
510
+ let endLine: number | undefined;
511
+
512
+ if (ts.isMethodDeclaration(node) && node.name) {
513
+ methodName = node.name.getText(sourceFile);
514
+ const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
515
+ const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
516
+ startLine = start.line + 1;
517
+ endLine = end.line + 1;
518
+ } else if (ts.isFunctionDeclaration(node) && node.name) {
519
+ methodName = node.name.getText(sourceFile);
520
+ const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
521
+ const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
522
+ startLine = start.line + 1;
523
+ endLine = end.line + 1;
524
+ } else if (ts.isArrowFunction(node)) {
525
+ if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
526
+ methodName = node.parent.name.getText(sourceFile);
527
+ const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
528
+ const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
529
+ startLine = start.line + 1;
530
+ endLine = end.line + 1;
531
+ }
532
+ }
533
+
534
+ if (methodName && startLine !== undefined && endLine !== undefined) {
535
+ methods.push({
536
+ name: methodName,
537
+ line: startLine,
538
+ endLine: endLine,
539
+ lines: endLine - startLine + 1,
540
+ disableInfo: getDisableInfo(fileLines, startLine),
541
+ });
542
+ }
543
+
544
+ ts.forEachChild(node, visit);
545
+ }
546
+
547
+ visit(sourceFile);
548
+ return methods;
549
+ }
550
+
551
+ /**
552
+ * Check if a method has any changes within its line range
553
+ */
554
+ function methodHasChanges(method: MethodInfo, changedLineNumbers: Set<number>): boolean {
555
+ for (let line = method.line; line <= method.endLine; line++) {
556
+ if (changedLineNumbers.has(line)) return true;
557
+ }
558
+ return false;
559
+ }
560
+
561
+ /**
562
+ * Check a NEW method and return violation if applicable
563
+ */
564
+ function checkNewMethodViolation(file: string, method: MethodInfo, disableAllowed: boolean): MethodViolation | null {
565
+ const disableType = method.disableInfo.type;
566
+ const isExpired = method.disableInfo.isExpired;
567
+ const disableDate = method.disableInfo.date;
568
+
569
+ if (!disableAllowed) {
570
+ // When disableAllowed is false, skip NEW methods without escape (let validate-new-methods handle)
571
+ if (disableType === 'none') return null;
572
+ return { file, methodName: method.name, line: method.line, lines: method.lines };
573
+ }
574
+
575
+ if (disableType === 'full' && isExpired) {
576
+ return { file, methodName: method.name, line: method.line, lines: method.lines, expiredDisable: true, expiredDate: disableDate };
577
+ }
578
+ if (disableType !== 'new-only') return null;
579
+
580
+ if (isExpired) {
581
+ return { file, methodName: method.name, line: method.line, lines: method.lines, expiredDisable: true, expiredDate: disableDate };
582
+ }
583
+ return { file, methodName: method.name, line: method.line, lines: method.lines };
584
+ }
585
+
586
+ /**
587
+ * Check a MODIFIED method and return violation if applicable
588
+ */
589
+ function checkModifiedMethodViolation(file: string, method: MethodInfo, disableAllowed: boolean): MethodViolation | null {
590
+ const disableType = method.disableInfo.type;
591
+ const isExpired = method.disableInfo.isExpired;
592
+ const disableDate = method.disableInfo.date;
593
+
594
+ if (!disableAllowed) {
595
+ return { file, methodName: method.name, line: method.line, lines: method.lines };
596
+ }
597
+ if (disableType === 'full' && !isExpired) {
598
+ // Valid escape, no violation
599
+ return null;
600
+ }
601
+ if (disableType === 'full' && isExpired) {
602
+ return { file, methodName: method.name, line: method.line, lines: method.lines, expiredDisable: true, expiredDate: disableDate };
603
+ }
604
+ return { file, methodName: method.name, line: method.line, lines: method.lines };
605
+ }
606
+
607
+ /**
608
+ * Find methods that exceed the limit.
609
+ * Checks NEW methods with escape hatches and MODIFIED methods.
610
+ */
611
+ function findViolations(
612
+ workspaceRoot: string,
613
+ changedFiles: string[],
614
+ base: string,
615
+ limit: number,
616
+ disableAllowed: boolean,
617
+ head?: string
618
+ ): MethodViolation[] {
619
+ const violations: MethodViolation[] = [];
620
+
621
+ for (const file of changedFiles) {
622
+ const diff = getFileDiff(workspaceRoot, file, base, head);
623
+ if (!diff) continue;
624
+
625
+ const newMethodNames = findNewMethodSignaturesInDiff(diff);
626
+ const changedLineNumbers = getChangedLineNumbers(diff);
627
+ if (changedLineNumbers.size === 0) continue;
628
+
629
+ const methods = findMethodsInFile(file, workspaceRoot);
630
+
631
+ for (const method of methods) {
632
+ const disableType = method.disableInfo.type;
633
+ const isExpired = method.disableInfo.isExpired;
634
+
635
+ // Skip methods with valid, non-expired full escape - unless disableAllowed is false
636
+ if (disableAllowed && disableType === 'full' && !isExpired) continue;
637
+ if (method.lines <= limit) continue;
638
+
639
+ const isNewMethod = newMethodNames.has(method.name);
640
+
641
+ if (isNewMethod) {
642
+ const violation = checkNewMethodViolation(file, method, disableAllowed);
643
+ if (violation) violations.push(violation);
644
+ } else if (methodHasChanges(method, changedLineNumbers)) {
645
+ const violation = checkModifiedMethodViolation(file, method, disableAllowed);
646
+ if (violation) violations.push(violation);
647
+ }
648
+ }
649
+ }
650
+
651
+ return violations;
652
+ }
653
+
654
+ /**
655
+ * Auto-detect the base branch by finding the merge-base with origin/main.
656
+ */
657
+ function detectBase(workspaceRoot: string): string | null {
658
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
659
+ try {
660
+ const mergeBase = execSync('git merge-base HEAD origin/main', {
661
+ cwd: workspaceRoot,
662
+ encoding: 'utf-8',
663
+ stdio: ['pipe', 'pipe', 'pipe'],
664
+ }).trim();
665
+
666
+ if (mergeBase) {
667
+ return mergeBase;
668
+ }
669
+ } catch (err: unknown) {
670
+ //const error = toError(err);
671
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
672
+ try {
673
+ const mergeBase = execSync('git merge-base HEAD main', {
674
+ cwd: workspaceRoot,
675
+ encoding: 'utf-8',
676
+ stdio: ['pipe', 'pipe', 'pipe'],
677
+ }).trim();
678
+
679
+ if (mergeBase) {
680
+ return mergeBase;
681
+ }
682
+ } catch (err2: unknown) {
683
+ //const error2 = toError(err2);
684
+ // Ignore
685
+ }
686
+ }
687
+ return null;
688
+ }
689
+
690
+ /**
691
+ * Report violations to console
692
+ */
693
+ // webpieces-disable max-lines-new-methods -- Error output formatting with multiple message sections
694
+ function reportViolations(violations: MethodViolation[], limit: number, disableAllowed: boolean): void {
695
+ console.error('');
696
+ console.error('\u274c Modified methods exceed ' + limit + ' lines!');
697
+ console.error('');
698
+ console.error('\ud83d\udcda When you modify a method, you must bring it under ' + limit + ' lines.');
699
+ console.error(' This rule encourages GRADUAL cleanup so even though you did not cause it,');
700
+ console.error(' you touched it, so you should fix now as part of your PR');
701
+ console.error(' (this is for vibe coding and AI to fix as it touches things).');
702
+ console.error(' You can refactor to stay under the limit 50% of the time. If not feasible, use the escape hatch.');
703
+ console.error('');
704
+ console.error(
705
+ '\u26a0\ufe0f *** READ .webpieces/instruct-ai/webpieces.methodsize.md for detailed guidance on how to fix this easily *** \u26a0\ufe0f'
706
+ );
707
+ console.error('');
708
+
709
+ for (const v of violations) {
710
+ if (v.expiredDisable) {
711
+ console.error(` \u274c ${v.file}:${v.line}`);
712
+ console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${limit})`);
713
+ console.error(` \u23f0 EXPIRED DISABLE: Your disable comment dated ${v.expiredDate ?? 'unknown'} has expired (>1 month old).`);
714
+ console.error(` You must either FIX the method or UPDATE the date to get another month.`);
715
+ } else {
716
+ console.error(` \u274c ${v.file}:${v.line}`);
717
+ console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${limit})`);
718
+ }
719
+ }
720
+ console.error('');
721
+
722
+ // Only show escape hatch instructions when disableAllowed is true
723
+ if (disableAllowed) {
724
+ console.error(' You can disable this error, but you will be forced to fix again in 1 month');
725
+ console.error(' since 99% of methods can be less than ' + limit + ' lines of code.');
726
+ console.error('');
727
+ console.error(' Use escape with DATE (expires in 1 month):');
728
+ console.error(` // webpieces-disable max-lines-modified ${getTodayDateString()} -- [your reason]`);
729
+ console.error('');
730
+ } else {
731
+ console.error(' \u26a0\ufe0f disableAllowed is false - disable comments are NOT allowed.');
732
+ console.error(' This rule must be met and cannot be disabled since nx.json disableAllowed is set to false.');
733
+ console.error(' You MUST refactor to reduce method size.');
734
+ console.error('');
735
+ console.error(' For a major refactor, a human can add "ignoreModifiedUntilEpoch" to nx.json validate-code options.');
736
+ console.error(' This is an expiry timestamp (epoch ms) for when we start forcing everyone to meet size rules again.');
737
+ console.error(' Sometimes for speed, we allow methods to expand during a refactor and over time,');
738
+ console.error(' each PR reduces methods as they get touched.');
739
+ console.error(' AI agents should NOT add ignoreModifiedUntilEpoch - ask a human to do it.');
740
+ console.error('');
741
+ }
742
+ }
743
+
744
+ export default async function runValidator(
745
+ options: ValidateModifiedMethodsOptions,
746
+ workspaceRoot: string
747
+ ): Promise<ExecutorResult> {
748
+ const limit = options.limit ?? 80;
749
+ const mode: MethodMaxLimitMode = options.mode ?? 'NEW_AND_MODIFIED_METHODS';
750
+ const disableAllowed = options.disableAllowed ?? true;
751
+
752
+ // Skip validation entirely if mode is OFF
753
+ if (mode === 'OFF') {
754
+ console.log('\n\u23ed\ufe0f Skipping modified method validation (mode: OFF)');
755
+ console.log('');
756
+ return { success: true };
757
+ }
758
+
759
+ // If NX_HEAD is set (via nx affected --head=X), use it; otherwise compare to working tree
760
+ let base = process.env['NX_BASE'];
761
+ const head = process.env['NX_HEAD'];
762
+
763
+ if (!base) {
764
+ base = detectBase(workspaceRoot) ?? undefined;
765
+
766
+ if (!base) {
767
+ console.log('\n\u23ed\ufe0f Skipping modified method validation (could not detect base branch)');
768
+ console.log(' To run explicitly: nx affected --target=validate-modified-methods --base=origin/main');
769
+ console.log('');
770
+ return { success: true };
771
+ }
772
+
773
+ console.log('\n\ud83d\udccf Validating Modified Method Sizes (auto-detected base)\n');
774
+ } else {
775
+ console.log('\n\ud83d\udccf Validating Modified Method Sizes\n');
776
+ }
777
+
778
+ console.log(` Base: ${base}`);
779
+ console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
780
+ console.log(` Mode: ${mode}`);
781
+ console.log(` Limit for modified methods: ${limit}`);
782
+ console.log(` Disable allowed: ${disableAllowed}${!disableAllowed ? ' (no escape hatch)' : ''}`);
783
+ console.log('');
784
+
785
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
786
+ try {
787
+ const changedFiles = getChangedTypeScriptFiles(workspaceRoot, base, head);
788
+
789
+ if (changedFiles.length === 0) {
790
+ console.log('\u2705 No TypeScript files changed');
791
+ return { success: true };
792
+ }
793
+
794
+ console.log(`\ud83d\udcc2 Checking ${changedFiles.length} changed file(s)...`);
795
+
796
+ const violations = findViolations(workspaceRoot, changedFiles, base, limit, disableAllowed, head);
797
+
798
+ if (violations.length === 0) {
799
+ console.log('\u2705 All modified methods are under ' + limit + ' lines');
800
+ return { success: true };
801
+ }
802
+
803
+ writeTmpInstructions(workspaceRoot);
804
+ reportViolations(violations, limit, disableAllowed);
805
+ return { success: false };
806
+ } catch (err: unknown) {
807
+ //const error = toError(err);
808
+ const error = err instanceof Error ? err : new Error(String(err));
809
+ console.error('\u274c Modified method validation failed:', error.message);
810
+ return { success: false };
811
+ }
812
+ }