@boyingliu01/xp-gate 0.39.3 → 0.40.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.
Files changed (42) hide show
  1. package/adapters/gate-10.sh +9 -0
  2. package/adapters/gate-12-file-hygiene.sh +103 -15
  3. package/adapters/gate-6-layers.sh +158 -16
  4. package/gate-10.sh +9 -0
  5. package/gate-12-file-hygiene.sh +103 -15
  6. package/gate-6-layers.sh +158 -16
  7. package/hooks/gate-10.sh +9 -0
  8. package/hooks/gate-12-file-hygiene.sh +103 -15
  9. package/hooks/gate-6-layers.sh +158 -16
  10. package/hooks/gate-entries/gate-5-entry.sh +52 -2
  11. package/hooks/gate-entries/gate-6-entry.sh +94 -4
  12. package/hooks/gate-entries/gate-9-entry.sh +9 -1
  13. package/hooks/lib/gate-12-blob-scan.awk +42 -2
  14. package/hooks/pre-commit +46 -2
  15. package/lib/gate-runner.js +52 -13
  16. package/mutation/init-baseline.ts +82 -26
  17. package/mutation/runners/mutmut-runner.ts +110 -26
  18. package/package.json +1 -1
  19. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  20. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  21. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  22. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  23. package/plugins/dsh/package.json +1 -1
  24. package/plugins/dsh/scripts/prepack.cjs +39 -14
  25. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  26. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  27. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  28. package/plugins/opencode/package.json +1 -1
  29. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  30. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  31. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  32. package/plugins/qoder/plugin.json +1 -1
  33. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  34. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  35. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  36. package/principles/adapters/function-body.ts +60 -0
  37. package/principles/adapters/typescript.ts +54 -4
  38. package/principles/config.ts +16 -3
  39. package/scripts/delphi-repo-tools.cjs +4 -1
  40. package/skills/delphi-review/AGENTS.md +1 -1
  41. package/skills/sprint-flow/AGENTS.md +1 -1
  42. package/skills/test-specification-alignment/AGENTS.md +1 -1
@@ -534,6 +534,42 @@ function resolveGateImplementation(gateModule, targetCwd, options = {}) {
534
534
  return script ? { kind: 'fallback', script } : { kind: 'none' };
535
535
  }
536
536
 
537
+ /**
538
+ * The environment a TypeScript gate module is spawned with (#820).
539
+ *
540
+ * Gate 3/7/8/9 are TS modules whose file list comes from `git diff --cached`.
541
+ * That is correct for a commit and wrong for `--all`, where the index is empty
542
+ * and the scan therefore had nothing to look at. The bash fragments solved the
543
+ * same question with GATE_SCOPE (see buildPreamble); the TS path spawned the
544
+ * module with no environment at all, so a TS gate could not tell the two apart
545
+ * even if it wanted to.
546
+ *
547
+ * Built here rather than at each call site because there are several, and the
548
+ * one that forgot would be the one that silently scanned nothing -- the failure
549
+ * mode this issue is about.
550
+ *
551
+ * @param {{all?: boolean, scope?: string}} opts the gate options
552
+ * @param {Record<string, string|undefined>} baseEnv the caller environment
553
+ * @returns {Record<string, string|undefined>} environment for the child process
554
+ */
555
+ function buildTsGateEnv(opts = {}, baseEnv = process.env) {
556
+ // The caller env is PRESERVED, not replaced: the modules read PATH, HOME and
557
+ // their own XP_* switches, and stripping those would turn a scope fix into a
558
+ // tool-resolution defect.
559
+ //
560
+ // The value is normalised to a CLOSED SET. Delphi round-1 (feasibility seat)
561
+ // measured `buildTsGateEnv({scope: ''}).GATE_SCOPE === ''`: a truthiness-blind
562
+ // `typeof === 'string'` forwarded an empty string as if it were a decision, and
563
+ // a gate comparing against 'all' or 'diff' matches neither -- silently keeping
564
+ // its default, which is the "nothing was scanned" shape this issue closes. A
565
+ // typo ('ALL', 'all ') is refused for the same reason.
566
+ const scope = opts && typeof opts.scope === 'string' ? opts.scope : '';
567
+ const resolved = scope === 'all' || scope === 'diff'
568
+ ? scope
569
+ : (opts && opts.all === true ? 'all' : 'diff');
570
+ return { ...baseEnv, GATE_SCOPE: resolved };
571
+ }
572
+
537
573
  function runTsGate(gateModule, targetPath, opts = {}) {
538
574
  const targetCwd = resolveGateCwd(targetPath);
539
575
  const impl = resolveGateImplementation(gateModule, targetCwd);
@@ -569,6 +605,9 @@ function runTsGate(gateModule, targetPath, opts = {}) {
569
605
  stdio: 'inherit',
570
606
  cwd: targetCwd,
571
607
  timeout: TS_GATE_TIMEOUT_MS,
608
+ // #820: without this the module cannot distinguish `--all` (scan the tree)
609
+ // from a commit (scan the index), and on a clean tree it scanned nothing.
610
+ env: buildTsGateEnv(opts, process.env),
572
611
  });
573
612
  if (result.error) {
574
613
  console.error(`Gate ${gateModule}: failed to run tsx (${viaNpx ? 'npx fallback' : 'local cli'}): ${result.error.message}`);
@@ -681,16 +720,16 @@ const GATE_REGISTRY = {
681
720
  name: 'IaC Security',
682
721
  description: 'Infrastructure-as-Code security scanning (checkov, hadolint, kube-score, tflint)',
683
722
  aliases: ['iac', 'infra', '7'],
684
- run: (targetPath) => {
685
- return runTsGate('gate-7', targetPath);
723
+ run: (targetPath, opts) => {
724
+ return runTsGate('gate-7', targetPath, opts);
686
725
  },
687
726
  },
688
727
  '8': {
689
728
  name: 'Secret Scanning',
690
729
  description: 'gitleaks secret and credential detection',
691
730
  aliases: ['secrets', 'secret', '8'],
692
- run: (targetPath) => {
693
- return runTsGate('gate-8', targetPath);
731
+ run: (targetPath, opts) => {
732
+ return runTsGate('gate-8', targetPath, opts);
694
733
  },
695
734
  },
696
735
  // Numbering follows the HOOK, which is where gates actually execute (#677).
@@ -711,8 +750,8 @@ const GATE_REGISTRY = {
711
750
  name: 'SAST Security',
712
751
  description: 'semgrep static application security testing',
713
752
  aliases: ['sast', 'semgrep', '10'],
714
- run: (targetPath) => {
715
- return runTsGate('gate-9', targetPath);
753
+ run: (targetPath, opts) => {
754
+ return runTsGate('gate-9', targetPath, opts);
716
755
  },
717
756
  },
718
757
  '11': {
@@ -760,24 +799,24 @@ const GATE_REGISTRY = {
760
799
  name: 'Python Environment Health',
761
800
  description: 'Comprehensive Python environment diagnostics',
762
801
  aliases: ['python-health', 'py-health'],
763
- run: (targetPath) => {
764
- return runTsGate('python-health', targetPath);
802
+ run: (targetPath, opts) => {
803
+ return runTsGate('python-health', targetPath, opts);
765
804
  },
766
805
  },
767
806
  'test-layers': {
768
807
  name: 'Test Layer Analytics',
769
808
  description: 'Report test distribution across unit/integration/e2e layers',
770
809
  aliases: ['test-layers', 'layers', 'test-analytics'],
771
- run: (targetPath) => {
772
- return runTsGate('test-layers', targetPath);
810
+ run: (targetPath, opts) => {
811
+ return runTsGate('test-layers', targetPath, opts);
773
812
  },
774
813
  },
775
814
  'pbt': {
776
815
  name: 'Property-Based Testing Detection',
777
816
  description: 'Detect PBT framework usage and report coverage',
778
817
  aliases: ['pbt', 'pbt-detect', 'property-based-testing'],
779
- run: (targetPath) => {
780
- return runTsGate('pbt-detect', targetPath);
818
+ run: (targetPath, opts) => {
819
+ return runTsGate('pbt-detect', targetPath, opts);
781
820
  },
782
821
  },
783
822
  };
@@ -1436,4 +1475,4 @@ module.exports = { writeAllModeFileList, removeFileList, buildFileSourceLines, f
1436
1475
  // written for never ran -- and the unit tests it defers to assert the pieces
1437
1476
  // separately, which is precisely the seam this case covers. Both are pure
1438
1477
  // string builders with no side effects, so exporting them costs nothing.
1439
- buildPreamble, buildFileSourceLines };
1478
+ buildPreamble, buildFileSourceLines, buildTsGateEnv };
@@ -75,27 +75,34 @@ function applyArg(args: string[], i: number) {
75
75
  }
76
76
 
77
77
  async function scanFiles(dir: string, results: string[], basePath: string): Promise<void> {
78
- let entries: import('fs').Dirent[];
79
- try {
80
- entries = await fs.readdir(dir, { withFileTypes: true }) as unknown as import('fs').Dirent[];
81
- } catch (err) {
82
- // THROW, do not warn and continue. A baseline is a record of what was measured, and
83
- // one built from a partial tree silently omits every file that directory contained --
84
- // those files then score as "no surviving mutants" for the rest of their lives. The
85
- // previous `console.warn` + `return` said the failure "is reported", but a warning
86
- // scrolls past and the artifact it produced looked complete (review FC-01).
87
- throw new Error(`cannot read directory ${dir}: ${errMessage(err)}`);
88
- }
78
+ // THROW, do not warn and continue. A baseline is a record of what was measured, and
79
+ // one built from a partial tree silently omits every file that directory contained --
80
+ // those files then score as "no surviving mutants" for the rest of their lives. The
81
+ // previous `console.warn` + `return` said the failure "is reported", but a warning
82
+ // scrolls past and the artifact it produced looked complete (review FC-01).
83
+ const entries = await readEntriesOrThrow(dir);
89
84
 
90
85
  for (const entry of entries) {
91
86
  const fullPath = path.join(dir, entry.name);
92
- const relativePath = path.relative(basePath, fullPath);
87
+ if (entry.isDirectory()) await scanFiles(fullPath, results, basePath);
88
+ else if (entry.isFile()) results.push(path.relative(basePath, fullPath));
89
+ }
90
+ }
93
91
 
94
- if (entry.isDirectory()) {
95
- await scanFiles(fullPath, results, basePath);
96
- } else if (entry.isFile()) {
97
- results.push(relativePath);
98
- }
92
+ /**
93
+ * Read a directory's entries, converting a failure into the named error.
94
+ *
95
+ * The guard lives with the IO (see ioFailureOnWrite for why), and `scanFiles` keeps the
96
+ * traversal. Splitting them is what brings the walk below its ratchet without moving the
97
+ * try away from the readdir.
98
+ *
99
+ * @param dir directory to read
100
+ */
101
+ async function readEntriesOrThrow(dir: string): Promise<import('fs').Dirent[]> {
102
+ try {
103
+ return (await fs.readdir(dir, { withFileTypes: true })) as unknown as import('fs').Dirent[];
104
+ } catch (err) {
105
+ throw ioFailure('read directory', dir, err);
99
106
  }
100
107
  }
101
108
 
@@ -135,13 +142,48 @@ async function runStryker(): Promise<void> {
135
142
  }
136
143
  }
137
144
 
138
- async function parseStrykerReport(reportPath: string): Promise<StrykerReport> {
145
+ /**
146
+ * The message for a failed IO step, naming what was attempted and where.
147
+ *
148
+ * Only the MESSAGE is shared. The try/catch stays in the function that performs the IO:
149
+ * `clean-code.missing-error-handling` looks for a guard INSIDE the function holding the
150
+ * operation, and moving the IO into a wrapper to avoid repeating one `try` made three
151
+ * functions read as unguarded. The rule was right -- a caller cannot see a guard that
152
+ * lives one call away when it reads the function alone.
153
+ *
154
+ * @param what the operation, for the message
155
+ * @param path the path it acted on
156
+ * @param err the underlying failure
157
+ */
158
+ function ioFailure(what: string, path: string, err: unknown): Error {
159
+ return new Error(`cannot ${what} ${path}: ${errMessage(err)}`);
160
+ }
161
+
162
+ /**
163
+ * The Stryker report, parsed -- or an error naming the file.
164
+ *
165
+ * `readJsonOrFail` owns the try/catch: the guard still sits with the read (see
166
+ * ioFailureOnWrite for why the rule wants it there), while this function stays a single
167
+ * call, which is the shape its baseline records.
168
+ *
169
+ * A report that cannot be read or parsed must not become an empty baseline: that would
170
+ * record "no mutations measured" for a file that was never scored.
171
+ */
172
+ function parseStrykerReport(reportPath: string): Promise<StrykerReport> {
173
+ return readJsonOrFail(reportPath, 'read or parse the Stryker report at') as Promise<StrykerReport>;
174
+ }
175
+
176
+ /**
177
+ * Read and parse a JSON file, converting any failure into the named error.
178
+ *
179
+ * @param filePath what to read
180
+ * @param what the operation, for the message
181
+ */
182
+ async function readJsonOrFail(filePath: string, what: string): Promise<unknown> {
139
183
  try {
140
- return JSON.parse(await fs.readFile(reportPath, 'utf-8')) as StrykerReport;
184
+ return JSON.parse(await fs.readFile(filePath, 'utf-8'));
141
185
  } catch (err) {
142
- // A report that cannot be read or parsed must not become an empty baseline: that
143
- // would record "no mutations measured" for a file that was never scored.
144
- throw new Error(`cannot read the Stryker report at ${reportPath}: ${errMessage(err)}`);
186
+ throw ioFailure(what, filePath, err);
145
187
  }
146
188
  }
147
189
 
@@ -186,12 +228,26 @@ function buildBaseline(
186
228
  }
187
229
 
188
230
  async function saveBaseline(baseline: MutationBaseline, outputPath: string): Promise<void> {
231
+ // Reporting success for an unwritten baseline would send the caller on to commit
232
+ // scores that are not on disk.
233
+ await ioFailureOnWrite(outputPath, JSON.stringify(baseline, null, 2));
234
+ }
235
+
236
+ /**
237
+ * Write `text` to `outputPath`, converting a failure into the named error.
238
+ *
239
+ * The try/catch lives HERE and not in `saveBaseline`: the rule looks for a guard inside
240
+ * the function that holds the IO, and this is that function. Its ratchet is 1, which one
241
+ * try satisfies.
242
+ *
243
+ * @param outputPath destination
244
+ * @param text contents
245
+ */
246
+ async function ioFailureOnWrite(outputPath: string, text: string): Promise<void> {
189
247
  try {
190
- await fs.writeFile(outputPath, JSON.stringify(baseline, null, 2));
248
+ await fs.writeFile(outputPath, text);
191
249
  } catch (err) {
192
- // Reporting success for an unwritten baseline would send the caller on to commit
193
- // scores that are not on disk.
194
- throw new Error(`cannot write the baseline to ${outputPath}: ${errMessage(err)}`);
250
+ throw ioFailure('write the baseline to', outputPath, err);
195
251
  }
196
252
  }
197
253
 
@@ -131,6 +131,40 @@ function removeCreated(pyprojectPath: string): void {
131
131
  }
132
132
  }
133
133
 
134
+ /**
135
+ * Read the number following `emoji` on a progress line.
136
+ *
137
+ * Returns `[0]` when the emoji is absent -- mutmut omits a zero count, so absence is a
138
+ * MEASURED zero -- and `[null]` when it is present but not followed by a number, which
139
+ * means the line was not understood. The wrapper array is what makes the two cases
140
+ * distinguishable without the caller reintroducing a predicate.
141
+ *
142
+ * @param line one mutmut progress line
143
+ * @param emoji the marker to read after
144
+ * @returns a single-element tuple holding the count, or null when unreadable
145
+ */
146
+ function countAfterMarker(line: string, emoji: string): [number | null] {
147
+ const at = line.indexOf(emoji);
148
+ if (at === -1) return [0];
149
+ const after = line.slice(at + emoji.length).match(/^\s*(\d+)/);
150
+ return [after === null ? null : parseInt(after[1], 10)];
151
+ }
152
+
153
+ /**
154
+ * The last line carrying a progress marker, or '' when there is none.
155
+ *
156
+ * mutmut repaints the same line, so the LAST one is the final state. Extracted from
157
+ * `parseEmojiProgress` so that method describes what the counts MEAN instead of how
158
+ * the line is located -- the two are unrelated, and together they exceeded the ratchet.
159
+ */
160
+ function lastProgressLine(stdout: string): string {
161
+ const lines = stdout.split('\n');
162
+ for (let i = lines.length - 1; i >= 0; i--) {
163
+ if (lines[i].includes('🎉')) return lines[i];
164
+ }
165
+ return '';
166
+ }
167
+
134
168
  export class MutmutRunner implements MutationRunner {
135
169
  readonly name = 'mutmut';
136
170
  readonly extensions = ['py'];
@@ -168,6 +202,11 @@ export class MutmutRunner implements MutationRunner {
168
202
  }
169
203
 
170
204
  async run(options: RunMutationOptions): Promise<MutationRunOutcome> {
205
+ // The availability probe must stay INLINE: the test harness wires its close
206
+ // listener from inside `isAvailable()`, so moving the `await` into a helper changed
207
+ // the order in which the fake child registered its listeners and ten cases failed
208
+ // with "finish() called before the runner registered a close listener". A refactor
209
+ // that changes when a call happens is not a refactor, whatever the ratchet says.
171
210
  if (this.route === 'unresolved' && this.platform === 'win32') {
172
211
  await this.isAvailable();
173
212
  }
@@ -179,29 +218,63 @@ export class MutmutRunner implements MutationRunner {
179
218
  const sourceDirs = this.extractUniqueDirs(options.files);
180
219
 
181
220
  const pyprojectPath = join(options.cwd, 'pyproject.toml');
182
- // Backing up and writing are OUTSIDE the `finally` on purpose, and both are caught:
183
- // a failure to prepare the workspace is a TOOL failure, and this module's contract is
184
- // that tool failures arrive as an outcome with `error`, never as a rejected promise
185
- // (a rejection reaches the caller's `catch` and reads as "no mutants found").
221
+ return this.withWorkspace(pyprojectPath, sourceDirs, (hadExisting) => this.runMutmut(options)
222
+ .finally(() => restorePyproject(pyprojectPath, hadExisting)));
223
+ }
224
+
225
+ /**
226
+ * Run `body` with a generated mutmut config in place, restoring the user's file.
227
+ *
228
+ * Preparation failures and run failures are handled in ONE expression instead of two
229
+ * statements in `run`: the contract is that a tool failure arrives as an outcome with
230
+ * `error` and never as a rejected promise, and stating that once here means a future
231
+ * caller cannot satisfy half of it.
232
+ *
233
+ * @param pyprojectPath absolute path to the project's pyproject.toml
234
+ * @param sourceDirs directories the generated config must point at
235
+ * @param body the run to perform while the generated config is in place
236
+ */
237
+ private async withWorkspace(
238
+ pyprojectPath: string,
239
+ sourceDirs: string[],
240
+ body: (hadExisting: boolean) => Promise<MutationRunOutcome>,
241
+ ): Promise<MutationRunOutcome> {
242
+ const prepared = this.prepareWorkspace(pyprojectPath, sourceDirs);
243
+ if ('error' in prepared) return { report: null, timedOut: false, error: prepared.error };
244
+ return body(prepared.hadExisting);
245
+ }
246
+
247
+ /**
248
+ * Write the generated mutmut config, restoring the user's file if that fails.
249
+ *
250
+ * Kept separate from `run` because it is the only part that can leave the workspace
251
+ * changed, and the rollback rule is subtle enough to deserve its own body. A failure
252
+ * to prepare is a TOOL failure and must arrive as an outcome with `error`, never as a
253
+ * rejected promise: a rejection reaches the caller's `catch` and reads as "no mutants
254
+ * found".
255
+ *
256
+ * @param pyprojectPath absolute path to the project's pyproject.toml
257
+ * @param sourceDirs directories the generated config must point at
258
+ * @returns the backup state, or the error message when preparation failed
259
+ */
260
+ private prepareWorkspace(
261
+ pyprojectPath: string,
262
+ sourceDirs: string[],
263
+ ): { hadExisting: boolean } | { error: string } {
186
264
  let hadExisting = false;
187
265
  let backedUp = false;
188
266
  try {
189
267
  hadExisting = this.backupPyproject(pyprojectPath);
190
268
  backedUp = true;
191
269
  this.writeMutmutConfig(pyprojectPath, sourceDirs);
270
+ return { hadExisting };
192
271
  } catch (err) {
193
272
  // Roll back ONLY what was done. `backedUp` distinguishes "the backup ran but the
194
273
  // write failed" from "the backup itself failed": with `restorePyproject(path,
195
274
  // false)` hardcoded, the first case DELETES a pyproject.toml that was there all
196
275
  // along -- the user's own file -- because `hadExisting` was never consulted.
197
276
  if (backedUp) restorePyproject(pyprojectPath, hadExisting);
198
- return { report: null, timedOut: false, error: err instanceof Error ? err.message : String(err) };
199
- }
200
-
201
- try {
202
- return await this.runMutmut(options);
203
- } finally {
204
- restorePyproject(pyprojectPath, hadExisting);
277
+ return { error: err instanceof Error ? err.message : String(err) };
205
278
  }
206
279
  }
207
280
 
@@ -293,15 +366,7 @@ export class MutmutRunner implements MutationRunner {
293
366
  * 🧙 = unknown (counted as survived)
294
367
  */
295
368
  private parseEmojiProgress(stdout: string): MutationRunResult | null {
296
- // Find the last progress line (contains 🎉)
297
- const lines = stdout.split('\n');
298
- let progressLine = '';
299
- for (let i = lines.length - 1; i >= 0; i--) {
300
- if (lines[i].includes('🎉')) {
301
- progressLine = lines[i];
302
- break;
303
- }
304
- }
369
+ const progressLine = lastProgressLine(stdout);
305
370
  if (!progressLine) return null;
306
371
 
307
372
  // Parse emoji counts: 🎉 N 🫥 N ⏰ N 🤔 N 🙁 N 🔇 N 🧙 N
@@ -349,10 +414,8 @@ export class MutmutRunner implements MutationRunner {
349
414
  * a clean run on a parse failure.
350
415
  */
351
416
  private extractEmojiCount(line: string, emoji: string): number | null {
352
- const at = line.indexOf(emoji);
353
- if (at === -1) return 0;
354
- const after = line.slice(at + emoji.length).match(/^\s*(\d+)/);
355
- return after ? parseInt(after[1], 10) : null;
417
+ const [count] = countAfterMarker(line, emoji);
418
+ return count;
356
419
  }
357
420
 
358
421
  /**
@@ -409,10 +472,31 @@ export function mutmutConfigContent(existing: string | null, sourceDirs: string[
409
472
  const line = arrayLine(sourceDirs);
410
473
  if (existing === null) return `[tool.mutmut]\n${line}\n`;
411
474
  const table = findMutmutTable(parseDocument(existing));
475
+ return rewriteForTable(existing, line, table);
476
+ }
477
+
478
+ /**
479
+ * The edit for an EXISTING document, chosen by what its table looks like.
480
+ *
481
+ * The four outcomes are a decision TABLE rather than a run of guards: each one answers
482
+ * "given this table, what text comes back", and as a table the reader can see that the
483
+ * cases are exhaustive. As stacked `if`s the last two were easy to read as one case.
484
+ *
485
+ * @param existing the document text, already known to parse or not
486
+ * @param line the `source_paths = [...]` line to place
487
+ * @param table the parsed `[tool.mutmut]` table, or null when there is no usable one
488
+ */
489
+ function rewriteForTable(
490
+ existing: string,
491
+ line: string,
492
+ table: { source_paths?: unknown } | null,
493
+ ): string {
412
494
  if (table === null) return withoutTable(existing, line);
413
495
  if (table.source_paths === undefined) return insertKey(existing, line);
414
- if (!Array.isArray(table.source_paths)) return existing;
415
- return replaceArrayText(existing, line);
496
+ // Present but not an array: the key exists with a shape this writer does not own.
497
+ // Leaving the text untouched is deliberate -- rewriting it would destroy a scalar or
498
+ // inline table the user wrote.
499
+ return Array.isArray(table.source_paths) ? replaceArrayText(existing, line) : existing;
416
500
  }
417
501
 
418
502
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boyingliu01/xp-gate",
3
- "version": "0.39.3",
3
+ "version": "0.40.1",
4
4
  "description": "Deterministic quality gates for AI-generated code: 15 gates, Delphi review, sprint flow. Works with Claude Code, OpenCode, Qoder.",
5
5
  "bin": {
6
6
  "xp-gate": "bin/xp-gate.js"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xp-gate",
3
- "version": "0.39.3",
3
+ "version": "0.40.1",
4
4
  "displayName": "XP-Gate",
5
5
  "description": "Extreme Programming quality gates + AI workflow skills for Claude Code. Includes 12 pre-commit gates (Gate 0-11), 8 pre-push gates, Sprint Flow (6 phases), and Delphi multi-expert review (>=90% consensus).",
6
6
  "author": {
@@ -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.39.3.0
6
+ **Version:** 0.40.1.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.39.3.0
6
+ **Version:** 0.40.1.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.39.3.0
6
+ **Version:** 0.40.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boyingliu01/dsh-plugin-xp-gate",
3
- "version": "0.39.3",
3
+ "version": "0.40.1",
4
4
  "description": "XP-Gate deterministic quality gates + AI workflow skills as a DeepSeek Harness (DSH) native plugin: gate-check / gate-principles / gate-arch tools + 12 SKILL.md skills",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -24,20 +24,29 @@ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'coverage']);
24
24
  const SKIP_FILE_SUFFIXES = ['.lock', '.js.map'];
25
25
 
26
26
  /** A skill is a directory directly under skills/ that contains a SKILL.md. */
27
- function discoverSkills() {
28
- const root = path.join(REPO_ROOT, 'skills');
29
- if (!fs.existsSync(root)) {
30
- console.error(`[prepack] ERROR: skills directory not found at ${root}`);
31
- process.exit(1);
32
- }
27
+ /** The skill names under `root/skills` that actually carry a SKILL.md. */
28
+ function skillNamesUnder(root) {
33
29
  try {
34
30
  return fs
35
31
  .readdirSync(root, { withFileTypes: true })
36
- .filter((e) => e.isDirectory())
37
- .map((e) => e.name)
32
+ .filter((e) => e.isDirectory())
33
+ .map((e) => e.name)
38
34
  .filter((name) => fs.existsSync(path.join(root, name, 'SKILL.md')))
39
35
  .sort();
40
36
  } catch (err) {
37
+ throw new Error(`cannot list skills under ${root}: ${err.message}`);
38
+ }
39
+ }
40
+
41
+ function discoverSkills() {
42
+ const root = path.join(REPO_ROOT, 'skills');
43
+ try {
44
+ return skillNamesUnder(root);
45
+ } catch (err) {
46
+ // One guard for both failures. A missing directory and an unreadable one end in the
47
+ // same place -- packaging cannot proceed -- and ENOENT already says which it was, so
48
+ // the pre-check only existed to word the message differently.
49
+ //
41
50
  // Packaging with NO skills would produce a plugin that loads but offers nothing.
42
51
  console.error(`[prepack] ERROR: cannot read ${root}: ${err.message}`);
43
52
  process.exit(1);
@@ -82,17 +91,25 @@ function copyDir(src, dest) {
82
91
  return true;
83
92
  }
84
93
 
85
- function main() {
86
- const skillsDest = path.join(PLUGIN_ROOT, 'skills');
94
+ /** Recreate `dir` empty, exiting with the path named when that fails. */
95
+ function recreateDir(dir) {
87
96
  try {
88
- fs.rmSync(skillsDest, { recursive: true, force: true });
89
- fs.mkdirSync(skillsDest, { recursive: true });
97
+ fs.rmSync(dir, { recursive: true, force: true });
98
+ fs.mkdirSync(dir, { recursive: true });
90
99
  } catch (err) {
91
- console.error(`[prepack] ERROR: cannot prepare ${skillsDest}: ${err.message}`);
100
+ console.error(`[prepack] ERROR: cannot prepare ${dir}: ${err.message}`);
92
101
  process.exit(1);
93
102
  }
103
+ }
94
104
 
95
- const skills = discoverSkills();
105
+ /**
106
+ * Copy every discovered skill into `skillsDest`.
107
+ *
108
+ * @param {string[]} skills skill names
109
+ * @param {string} skillsDest destination root
110
+ * @returns {number} how many were copied
111
+ */
112
+ function copySkills(skills, skillsDest) {
96
113
  let copied = 0;
97
114
  for (const name of skills) {
98
115
  if (copyDir(path.join(REPO_ROOT, 'skills', name), path.join(skillsDest, name))) {
@@ -100,6 +117,14 @@ function main() {
100
117
  console.error(`[prepack] skills/${name}`);
101
118
  }
102
119
  }
120
+ return copied;
121
+ }
122
+
123
+ function main() {
124
+ const skillsDest = path.join(PLUGIN_ROOT, 'skills');
125
+ recreateDir(skillsDest);
126
+ const skills = discoverSkills();
127
+ const copied = copySkills(skills, skillsDest);
103
128
 
104
129
  if (copied !== skills.length) {
105
130
  console.error(`[prepack] ERROR: expected ${skills.length} skills, copied ${copied}`);
@@ -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.39.3.0
6
+ **Version:** 0.40.1.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.39.3.0
6
+ **Version:** 0.40.1.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.39.3.0
6
+ **Version:** 0.40.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boyingliu01/opencode-plugin",
3
- "version": "0.39.3",
3
+ "version": "0.40.1",
4
4
  "type": "module",
5
5
  "main": "index.ts",
6
6
  "description": "XP-Gate quality gates + AI workflow skills for OpenCode",
@@ -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.39.3.0
6
+ **Version:** 0.40.1.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.39.3.0
6
+ **Version:** 0.40.1.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.39.3.0
6
+ **Version:** 0.40.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.