@boyingliu01/xp-gate 0.38.73 → 0.38.75

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 (32) hide show
  1. package/bin/xp-gate.js +17 -1
  2. package/lib/__tests__/doctor-signature-stability.test.js +55 -0
  3. package/lib/__tests__/doctor.test.js +6 -1
  4. package/lib/__tests__/gate2-verdict.test.js +126 -0
  5. package/lib/__tests__/issue-566-sync-hooks-backup.test.js +23 -16
  6. package/lib/__tests__/jscpd-entry-resolution.test.js +143 -0
  7. package/lib/__tests__/tsx-resolution.test.js +89 -0
  8. package/lib/doctor.js +99 -3
  9. package/lib/gate-runner.js +275 -41
  10. package/lib/mattpocock-license-verdict.json +1 -1
  11. package/lib/tsx-resolve.js +48 -0
  12. package/package.json +1 -1
  13. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  14. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  15. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  16. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  17. package/plugins/dsh/package.json +1 -1
  18. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  19. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  20. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  21. package/plugins/opencode/package.json +1 -1
  22. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  23. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  24. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  25. package/plugins/qoder/plugin.json +1 -1
  26. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  27. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  28. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  29. package/principles/adapters/php.ts +407 -5
  30. package/skills/delphi-review/AGENTS.md +1 -1
  31. package/skills/sprint-flow/AGENTS.md +1 -1
  32. package/skills/test-specification-alignment/AGENTS.md +1 -1
@@ -21,6 +21,41 @@ import { Adapter } from '../types';
21
21
  * with no name a human recognises) and arrow functions `fn($x) => ...`, which
22
22
  * have no brace body for the nesting rules to walk.
23
23
  */
24
+ /** Where a brace scan ended: the last depth-zero position, and whether it balanced. */
25
+ interface BraceScan {
26
+ endPos: number;
27
+ balanced: boolean;
28
+ }
29
+
30
+ /**
31
+ * Find the LAST index at which brace depth returned to zero, scanning `code` from
32
+ * `startPos`.
33
+ *
34
+ * The last crossing is the declaration's real closing brace: a nested class or
35
+ * closure sits INSIDE the declaration and so cannot be the last one at depth zero.
36
+ * The first crossing is deliberately not used -- measured, an unterminated heredoc
37
+ * leaves unmatched `{` in the text, so the first zero-crossing lands mid-body and
38
+ * reported a five-level `if` chain as depth 4.
39
+ *
40
+ * `balanced` is false when the scan never returns to zero, the signal that the
41
+ * input is malformed and no crossing is trustworthy.
42
+ */
43
+ function lastBalancedEnd(code: string, startPos: number): BraceScan {
44
+ let depth = 0;
45
+ let seenBrace = false;
46
+ let endPos = -1;
47
+ for (let i = startPos; i < code.length; i++) {
48
+ if (code[i] === '{') {
49
+ depth++;
50
+ seenBrace = true;
51
+ } else if (code[i] === '}') {
52
+ depth--;
53
+ if (seenBrace && depth === 0) endPos = i + 1;
54
+ }
55
+ }
56
+ return { endPos, balanced: depth === 0 };
57
+ }
58
+
24
59
  export class PhpAdapter extends BaseAdapter implements Adapter {
25
60
  detectLanguage(): string {
26
61
  const lower = this.filePath.toLowerCase();
@@ -43,17 +78,82 @@ export class PhpAdapter extends BaseAdapter implements Adapter {
43
78
  let match;
44
79
 
45
80
  while ((match = fnRegex.exec(this.fileContent)) !== null) {
81
+ const name = match[1];
46
82
  // A method whose name collides with a PHP keyword is not a declaration.
47
- if (match[1] === '__construct') {
48
- functionMatches.push(this.createCodeMatch(match[1], 'constructor', match.index));
49
- continue;
50
- }
51
- functionMatches.push(this.createCodeMatch(match[1], 'function', match.index));
83
+ const kind = name === '__construct' ? 'constructor' : 'function';
84
+ const found = this.createCodeMatch(name, kind, match.index);
85
+ this.annotateMetrics(found);
86
+ functionMatches.push(found);
52
87
  }
53
88
 
54
89
  return functionMatches;
55
90
  }
56
91
 
92
+ /**
93
+ * Cut the function body with heredoc/nowdoc awareness.
94
+ *
95
+ * The inherited implementation counts braces character by character, so a
96
+ * heredoc containing `{` grows its brace depth without any matching `}` in real
97
+ * code. Measured on a method whose heredoc held `{ { {`: the cut stopped inside
98
+ * the heredoc and the rest of the method -- including a five-level `if` chain --
99
+ * never reached the rules at all, reporting nestingDepth 1.
100
+ *
101
+ * Blanking the literals first means the brace scan only ever sees code, and the
102
+ * cut lands on the method's real closing brace. The returned text is the
103
+ * ORIGINAL slice, not the blanked one: `length` is a line count of the source as
104
+ * written, and `code` is what a human reads in a finding.
105
+ */
106
+ protected extractCodeBlock(startPos: number, maxFallback: number = 100): string {
107
+ const blanked = stripPhpLiterals(this.fileContent);
108
+ const scan = lastBalancedEnd(blanked, startPos);
109
+
110
+ // Unterminated heredoc: the text never rebalances, so no crossing is a real
111
+ // boundary. Fall back to the last `}` in the file rather than a boundary that
112
+ // is provably wrong; a malformed file must degrade to less checking, never to
113
+ // a quiet pass.
114
+ if (!scan.balanced) {
115
+ const lastClose = blanked.lastIndexOf('}');
116
+ return lastClose > startPos
117
+ ? this.fileContent.substring(startPos, lastClose + 1)
118
+ : this.fallbackCodeBlock(startPos, maxFallback);
119
+ }
120
+ if (scan.endPos <= 0) return this.fallbackCodeBlock(startPos, maxFallback);
121
+ return this.fileContent.substring(startPos, scan.endPos);
122
+ }
123
+
124
+ /**
125
+ * Add the fields the Gate 4 rules actually read.
126
+ *
127
+ * `createCodeMatch` supplies only {name, type, line, code}. Every rule that
128
+ * asks a question about a function's SHAPE reads `nestingDepth`, `paramCount`,
129
+ * `length` or `hasTryCatch` instead -- so without this, PHP matched the
130
+ * declaration and then silently satisfied nothing. Measured: identical
131
+ * five-level nesting reported one ERROR as `Same.ts` and "No violations found"
132
+ * as `Legacy.php`.
133
+ *
134
+ * This is the #446 shape the csharp adapter's comment documents: a missing
135
+ * field is invisible, because the rule finds nothing to report rather than
136
+ * reporting that it could not measure.
137
+ */
138
+ private annotateMetrics(target: unknown): void {
139
+ const m = target as Record<string, unknown>;
140
+ const body = typeof m.code === 'string' ? m.code : '';
141
+
142
+ // Strip literals ONCE and derive every metric from that view.
143
+ //
144
+ // `hasTryCatch` originally tested the RAW body, so a method whose only
145
+ // `try {` sat inside a string or a comment reported error handling it did not
146
+ // have -- measured: a method holding `$s = 'try { x } catch (E $e) { }'`
147
+ // returned true. missing-error-handling is the rule that consumes this field,
148
+ // so the mistake made the rule stay silent on a method with no catch at all.
149
+ const code = stripPhpLiterals(body);
150
+
151
+ m.length = body === '' ? 0 : body.split(/\r?\n/).length;
152
+ m.nestingDepth = measureNesting(code);
153
+ m.hasTryCatch = /\btry\s*\{/.test(code) && /\bcatch\s*[({]/.test(code);
154
+ m.paramCount = countParameters(code);
155
+ }
156
+
57
157
  extractClasses(): unknown[] {
58
158
  const classMatches = [];
59
159
  const classRegex = /(?:^|[\s;{}])class\s+(\w+)(?:\s+extends\s+([\w\\]+))?/g;
@@ -75,3 +175,305 @@ export class PhpAdapter extends BaseAdapter implements Adapter {
75
175
  return classMatches;
76
176
  }
77
177
  }
178
+
179
+ /**
180
+ * Deepest run of `{` in a function body.
181
+ *
182
+ * String literals and comments are blanked out first. PHP code is dense with
183
+ * braces inside strings (`sprintf('{{%s}}')`, JSON blobs, HTML templates) and the
184
+ * base class's `advanceBraceTracker` counts every one of them -- a method whose
185
+ * only "nesting" is a template string would be reported as deeply nested, and the
186
+ * rule would be turned off within a week.
187
+ *
188
+ * The body's own braces contribute one level, so a flat method reads 1. That
189
+ * matches how the csharp adapter measures and how the rule's threshold is tuned.
190
+ */
191
+ function measureNesting(stripped: string): number {
192
+ let depth = 0;
193
+ let maxDepth = 0;
194
+ for (const ch of stripped) {
195
+ if (ch === '{') {
196
+ depth++;
197
+ if (depth > maxDepth) maxDepth = depth;
198
+ } else if (ch === '}') {
199
+ depth--;
200
+ }
201
+ }
202
+ return maxDepth > 0 ? maxDepth : 0;
203
+ }
204
+
205
+ /**
206
+ * Blank one line comment starting at `start`, returning the replacement and the
207
+ * index of its terminating newline (or end of input).
208
+ */
209
+ function blankLineComment(code: string, start: number): { emit: string; last: number } {
210
+ let i = start;
211
+ let emit = '';
212
+ while (i < code.length && code[i] !== '\n') {
213
+ emit += ' ';
214
+ i++;
215
+ }
216
+ return { emit, last: i };
217
+ }
218
+
219
+ /** Blank one block comment, including its delimiters. */
220
+ function blankBlockComment(code: string, start: number): { emit: string; last: number } { let i = start + 2;
221
+ let emit = ' ';
222
+ while (i < code.length && !(code[i] === '*' && code[i + 1] === '/')) {
223
+ emit += ' ';
224
+ i++;
225
+ }
226
+ if (i < code.length) {
227
+ emit += ' ';
228
+ i++;
229
+ }
230
+ return { emit, last: i };
231
+ }
232
+
233
+ /** Blank one quoted string, keeping the delimiters so positions stay aligned. */
234
+ function blankQuoted(code: string, start: number): { emit: string; last: number } {
235
+ const quote = code[start];
236
+ let i = start + 1;
237
+ let emit = quote;
238
+ while (i < code.length && code[i] !== quote) {
239
+ // A backslash escapes the next character in both quoted forms.
240
+ if (code[i] === '\\') {
241
+ emit += ' ';
242
+ i += 2;
243
+ continue;
244
+ }
245
+ emit += ' ';
246
+ i++;
247
+ }
248
+ if (i < code.length) {
249
+ emit += quote;
250
+ i++;
251
+ }
252
+ return { emit, last: i };
253
+ }
254
+
255
+ /** A heredoc/nowdoc opener: `<<<SQL`, `<<<"SQL"`, `<<<'SQL'`. */
256
+ const HEREDOC_OPEN = /<<<[ \t]*(["']?)([A-Za-z_]\w*)\1[ \t]*\r?\n/y;
257
+
258
+ /**
259
+ * Blank a heredoc or nowdoc block from its `<<<` opener to its closing
260
+ * identifier.
261
+ *
262
+ * These MUST be stripped, and the earlier assumption that leaving them alone only
263
+ * caused under-counting was wrong -- measured, it caused false positives:
264
+ *
265
+ * function sqlTemplate() { $sql = <<<SQL { { { { { SQL; ... }
266
+ * -> nestingDepth 6 on a method with no nesting
267
+ * function heredocTry() { $s = <<<TXT try { x } catch (E $e) { } TXT; ... }
268
+ * -> hasTryCatch true with no try/catch in code
269
+ *
270
+ * deep-nesting's threshold is 4, so a SQL template or an inline CSS/JS block was
271
+ * enough to report a violation against correct code. False positives in a gate
272
+ * are resolved by switching the rule off, which is the expensive direction.
273
+ *
274
+ * The closing identifier must start a line (optional indentation, PHP 7.3+) and be
275
+ * followed by a non-identifier character, so a line whose content merely starts
276
+ * with the same word does not terminate the block early.
277
+ */
278
+ function blankHeredoc(code: string, start: number): { emit: string; last: number } | undefined {
279
+ HEREDOC_OPEN.lastIndex = start;
280
+ const opener = HEREDOC_OPEN.exec(code);
281
+ if (!opener) return undefined;
282
+
283
+ const terminator = opener[2];
284
+ let i = start + opener[0].length;
285
+ let emit = ' '.repeat(opener[0].length);
286
+ let closed = false;
287
+
288
+ while (i < code.length) {
289
+ const lineStart = i;
290
+ let lineEnd = code.indexOf('\n', i);
291
+ if (lineEnd < 0) lineEnd = code.length;
292
+ const line = code.slice(lineStart, lineEnd);
293
+ const trimmed = line.trimStart();
294
+
295
+ if (trimmed.startsWith(terminator)) {
296
+ const afterWord = trimmed.charAt(terminator.length);
297
+ // End of line, whitespace, or a statement/expression terminator -- not the
298
+ // start of a longer word, and not a comma either: PHP allows `SQL,` when the
299
+ // heredoc is an array element. Missing the comma case over-blanked silently,
300
+ // which is the same class of quiet failure as truncation.
301
+ if (afterWord === '' || /[\s;,\]})]/.test(afterWord)) {
302
+ emit += ' '.repeat(line.length);
303
+ i = lineEnd;
304
+ closed = true;
305
+ break;
306
+ }
307
+ }
308
+ emit += ' '.repeat(line.length);
309
+ if (lineEnd < code.length) {
310
+ emit += '\n';
311
+ i = lineEnd + 1;
312
+ } else {
313
+ i = lineEnd;
314
+ }
315
+ }
316
+
317
+ // A heredoc with no terminator is malformed source. Treating the opener as
318
+ // ordinary text keeps the rest of the method analysable, and the unmatched `{`
319
+ // inside the unterminated body then count as code. That is the honest reading:
320
+ // with no closing marker there is no way to know where the string ends, so the
321
+ // gate reports what the braces literally say rather than guessing a boundary.
322
+ //
323
+ // The alternative -- blanking to end-of-file -- silently disabled every rule for
324
+ // the rest of the method (measured: a five-level `if` chain reported depth 1 and
325
+ // length 4). A malformed file must degrade to less checking on that construct,
326
+ // never to a quiet pass on the whole method.
327
+ if (!closed) {
328
+ return { emit: code.slice(start, start + opener[0].length - 1), last: start + opener[0].length - 1 };
329
+ }
330
+ return { emit, last: i };
331
+ }
332
+
333
+ /**
334
+ * Recognise the literal form starting at `index`, or return undefined when the
335
+ * character is ordinary code.
336
+ *
337
+ * One dispatcher rather than an `if/else if` chain inside the scan loop: the
338
+ * chain measured CCN 13 on its own, over the Gate 3 block threshold, and the
339
+ * forms are a lookup rather than a cascade.
340
+ *
341
+ * `#` is checked before the heredoc opener would ever see it, and `<<<` is
342
+ * checked before `<` could be read as an operator, so the order of these tests is
343
+ * load-bearing rather than stylistic.
344
+ */
345
+ /**
346
+ * Single-character literal openers. `#` and both quote forms are unambiguous, so
347
+ * they need no lookahead and live in a table rather than in the branch chain.
348
+ */
349
+ const SINGLE_CHAR_LITERAL: Readonly<Record<string, (code: string, at: number) => { emit: string; last: number }>> = {
350
+ '#': blankLineComment,
351
+ "'": blankQuoted,
352
+ '"': blankQuoted,
353
+ };
354
+
355
+ function blankLiteralAt(code: string, index: number): { emit: string; last: number } | undefined {
356
+ const ch = code[index];
357
+
358
+ const single = SINGLE_CHAR_LITERAL[ch];
359
+ if (single) return single(code, index);
360
+
361
+ // `//` versus `/*`: same first character, so this needs lookahead.
362
+ if (ch === '/') {
363
+ if (code[index + 1] === '/') return blankLineComment(code, index);
364
+ return code[index + 1] === '*' ? blankBlockComment(code, index) : undefined;
365
+ }
366
+ // `<<<` opens a heredoc/nowdoc; a lone `<` is an operator.
367
+ if (ch === '<' && code[index + 1] === '<' && code[index + 2] === '<') {
368
+ return blankHeredoc(code, index);
369
+ }
370
+ return undefined;
371
+ }
372
+
373
+ /**
374
+ * Replace string/comment/heredoc contents with spaces, preserving length so brace
375
+ * positions stay meaningful.
376
+ *
377
+ * Covers every literal form PHP code actually uses: single- and double-quoted
378
+ * strings, `//` and `#` line comments, block comments, and heredoc/nowdoc blocks.
379
+ * It is still not a full lexer, but every remaining omission must fail in the
380
+ * UNDER-counting direction -- leaving a constructor out can only make a gate
381
+ * quieter, never fabricate a finding.
382
+ *
383
+ * Split into one helper per literal form because the single-loop version measured
384
+ * CCN 23: seven branch points sharing one index variable read as deeply nested
385
+ * even though each branch is trivial.
386
+ */
387
+ function stripPhpLiterals(code: string): string {
388
+ let out = '';
389
+ for (let i = 0; i < code.length; i++) {
390
+ const slice = blankLiteralAt(code, i);
391
+ if (!slice) {
392
+ out += code[i];
393
+ continue;
394
+ }
395
+ out += slice.emit;
396
+ // `last` is the index the helper stopped AT (the terminating newline or
397
+ // closing delimiter, already emitted). Resume just past it; the loop's own
398
+ // `i++` would otherwise consume one character twice.
399
+ i = slice.last;
400
+ }
401
+ return out;
402
+ }
403
+
404
+ /**
405
+ * What a parameter list scan found: the outermost-level comma count and whether
406
+ * any non-whitespace sat between the parentheses.
407
+ */
408
+ interface ParamScan {
409
+ commas: number;
410
+ sawContent: boolean;
411
+ }
412
+
413
+ /**
414
+ * Scan from `open` (the `(`) to its matching `)`, counting commas that separate
415
+ * parameters.
416
+ *
417
+ * ALL THREE bracket pairs are tracked, not just parentheses. A default value can
418
+ * be a short-array literal, and this scanner originally counted parens only:
419
+ * measured, `function shortArray($a = [1,2], $b = [3,4])` reported FOUR
420
+ * parameters instead of two. `too-many-params` blocks above 7, so a handful of
421
+ * array defaults turned correct code into a false block -- the expensive
422
+ * direction, and one a user resolves by disabling the rule.
423
+ *
424
+ * Curly braces are tracked for the same reason (`$a = ['k' => ['x' => 1]]`).
425
+ * Literals are already blanked by the caller, so braces inside strings do not
426
+ * reach this scan.
427
+ */
428
+ /** Nesting delta contributed by each bracket character. */
429
+ const BRACKET_DELTA: Readonly<Record<string, readonly [number, number, number]>> = {
430
+ '(': [1, 0, 0],
431
+ ')': [-1, 0, 0],
432
+ '[': [0, 1, 0],
433
+ ']': [0, -1, 0],
434
+ '{': [0, 0, 1],
435
+ '}': [0, 0, -1],
436
+ };
437
+
438
+ function scanParamList(stripped: string, open: number): ParamScan {
439
+ let parens = 0;
440
+ let brackets = 0;
441
+ let braces = 0;
442
+ let commas = 0;
443
+ let sawContent = false;
444
+ for (let i = open; i < stripped.length; i++) {
445
+ const ch = stripped[i];
446
+ const delta = BRACKET_DELTA[ch];
447
+
448
+ // Brackets are a table lookup, not a branch cascade: the cascade measured
449
+ // CCN 14-15 against a block threshold of 10 while each arm was one increment.
450
+ if (delta) {
451
+ parens += delta[0];
452
+ brackets += delta[1];
453
+ braces += delta[2];
454
+ if (parens === 0 && i > open) break;
455
+ continue;
456
+ }
457
+
458
+ if (!/\s/.test(ch)) sawContent = true;
459
+ // A comma separates parameters only at the list's own outermost level.
460
+ if (ch === ',' && parens === 1 && brackets === 0 && braces === 0) commas++;
461
+ }
462
+ return { commas, sawContent };
463
+ }
464
+
465
+ /**
466
+ * Count a declaration's parameters from its `code` (which starts at the
467
+ * `function` keyword and therefore includes the parameter list).
468
+ *
469
+ * Returns 0 for an empty list. Commas inside a default value -- array literals,
470
+ * nested calls, string content -- are not counted, because the scan only tallies
471
+ * at the list's outermost level.
472
+ */
473
+ function countParameters(stripped: string): number {
474
+ const open = stripped.indexOf('(');
475
+ if (open < 0) return 0;
476
+ const scan = scanParamList(stripped, open);
477
+ if (!scan.sawContent) return 0;
478
+ return scan.commas + 1;
479
+ }
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.73.0
6
+ **Version:** 0.38.75.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Delphi Consensus Review — multi-round anonymous expert review (≥90% threshold, exactly 3 experts with distinct executable model IDs). Supports design, requirements, and code-walkthrough modes.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.73.0
6
+ **Version:** 0.38.75.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **6-phase** development pipeline (v2.0 compact redesign, Issue #290): PREP → DESIGN → BUILD → VERIFY → SHIP → CLOSE. Phase 3/6 BUILD default build mode is **ralph-loop** (REQ-level iteration; each REQ starts from a clean context instead of accumulating one across REQs). HARD-GATE between DESIGN (2/6) and BUILD (3/6): design must pass Delphi review (≥90% consensus) before any coding.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.73.0
6
+ **Version:** 0.38.75.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.