@boyingliu01/xp-gate 0.39.2 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/adapters/gate-12-file-hygiene.sh +103 -15
  2. package/adapters/gate-6-layers.sh +158 -16
  3. package/gate-12-file-hygiene.sh +103 -15
  4. package/gate-6-layers.sh +158 -16
  5. package/hooks/gate-12-file-hygiene.sh +103 -15
  6. package/hooks/gate-6-layers.sh +158 -16
  7. package/hooks/gate-entries/gate-5-entry.sh +52 -2
  8. package/hooks/gate-entries/gate-6-entry.sh +86 -3
  9. package/hooks/lib/gate-12-blob-scan.awk +42 -2
  10. package/hooks/pre-commit +46 -2
  11. package/lib/gate-runner.js +52 -13
  12. package/mutation/init-baseline.ts +82 -26
  13. package/mutation/runners/mutmut-runner.ts +110 -26
  14. package/package.json +1 -1
  15. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  16. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  17. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  18. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  19. package/plugins/dsh/package.json +1 -1
  20. package/plugins/dsh/scripts/prepack.cjs +39 -14
  21. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  22. package/plugins/dsh/skills/reinstall-xp-gate/.architecture-skip +8 -0
  23. package/plugins/dsh/skills/reinstall-xp-gate/.github/workflows/test.yml +106 -0
  24. package/plugins/dsh/skills/reinstall-xp-gate/CHANGELOG.md +379 -0
  25. package/plugins/dsh/skills/reinstall-xp-gate/LICENSE +21 -0
  26. package/plugins/dsh/skills/reinstall-xp-gate/QUALITY-OVERVIEW.md +173 -0
  27. package/plugins/dsh/skills/reinstall-xp-gate/README.md +167 -0
  28. package/plugins/dsh/skills/reinstall-xp-gate/SKILL.md +271 -0
  29. package/plugins/dsh/skills/reinstall-xp-gate/TODO.md +253 -0
  30. package/plugins/dsh/skills/reinstall-xp-gate/VERSION +1 -0
  31. package/plugins/dsh/skills/reinstall-xp-gate/package.json +28 -0
  32. package/plugins/dsh/skills/reinstall-xp-gate/scripts/audit.mjs +193 -0
  33. package/plugins/dsh/skills/reinstall-xp-gate/scripts/coverage.mjs +140 -0
  34. package/plugins/dsh/skills/reinstall-xp-gate/scripts/hp-gate.mjs +175 -0
  35. package/plugins/dsh/skills/reinstall-xp-gate/scripts/install.mjs +64 -0
  36. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/agent-paths.mjs +67 -0
  37. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/agents.mjs +247 -0
  38. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/backups.mjs +96 -0
  39. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/baseline.mjs +101 -0
  40. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/ccn.mjs +124 -0
  41. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/delphi.mjs +61 -0
  42. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/fs-tree.mjs +108 -0
  43. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/gatecheck.mjs +290 -0
  44. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/json-file.mjs +37 -0
  45. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/mutations.mjs +154 -0
  46. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/platform.mjs +92 -0
  47. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/probes.mjs +128 -0
  48. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/proc.mjs +33 -0
  49. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/report.mjs +29 -0
  50. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/residue.mjs +188 -0
  51. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/selfsync.mjs +75 -0
  52. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/skills.mjs +121 -0
  53. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/spawn.mjs +181 -0
  54. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/testreport.mjs +26 -0
  55. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/tools.mjs +238 -0
  56. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/util.mjs +33 -0
  57. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/verdict.mjs +45 -0
  58. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/version.mjs +29 -0
  59. package/plugins/dsh/skills/reinstall-xp-gate/scripts/lib/xp-cli.mjs +66 -0
  60. package/plugins/dsh/skills/reinstall-xp-gate/scripts/mutation.mjs +132 -0
  61. package/plugins/dsh/skills/reinstall-xp-gate/scripts/preflight.mjs +75 -0
  62. package/plugins/dsh/skills/reinstall-xp-gate/scripts/reinstall.mjs +305 -0
  63. package/plugins/dsh/skills/reinstall-xp-gate/scripts/setup-wsl.sh +633 -0
  64. package/plugins/dsh/skills/reinstall-xp-gate/scripts/verify.mjs +239 -0
  65. package/plugins/dsh/skills/reinstall-xp-gate/tests/agents.test.mjs +168 -0
  66. package/plugins/dsh/skills/reinstall-xp-gate/tests/baseline.test.mjs +104 -0
  67. package/plugins/dsh/skills/reinstall-xp-gate/tests/ccn.test.mjs +87 -0
  68. package/plugins/dsh/skills/reinstall-xp-gate/tests/cleanup.test.mjs +128 -0
  69. package/plugins/dsh/skills/reinstall-xp-gate/tests/coverage.test.mjs +69 -0
  70. package/plugins/dsh/skills/reinstall-xp-gate/tests/delphi.test.mjs +78 -0
  71. package/plugins/dsh/skills/reinstall-xp-gate/tests/fixtures.mjs +61 -0
  72. package/plugins/dsh/skills/reinstall-xp-gate/tests/gatecheck-audit.test.mjs +157 -0
  73. package/plugins/dsh/skills/reinstall-xp-gate/tests/gatecheck.test.mjs +57 -0
  74. package/plugins/dsh/skills/reinstall-xp-gate/tests/mutation-anchors.test.mjs +49 -0
  75. package/plugins/dsh/skills/reinstall-xp-gate/tests/proc-contract.test.mjs +58 -0
  76. package/plugins/dsh/skills/reinstall-xp-gate/tests/proc.test.mjs +255 -0
  77. package/plugins/dsh/skills/reinstall-xp-gate/tests/report.test.mjs +66 -0
  78. package/plugins/dsh/skills/reinstall-xp-gate/tests/residue.test.mjs +278 -0
  79. package/plugins/dsh/skills/reinstall-xp-gate/tests/selfsync.test.mjs +70 -0
  80. package/plugins/dsh/skills/reinstall-xp-gate/tests/skills.test.mjs +171 -0
  81. package/plugins/dsh/skills/reinstall-xp-gate/tests/testreport.test.mjs +40 -0
  82. package/plugins/dsh/skills/reinstall-xp-gate/tests/timeout-budgets.test.mjs +38 -0
  83. package/plugins/dsh/skills/reinstall-xp-gate/tests/tools-leaf.test.mjs +323 -0
  84. package/plugins/dsh/skills/reinstall-xp-gate/tests/tools-probe.test.mjs +350 -0
  85. package/plugins/dsh/skills/reinstall-xp-gate/tests/tools.test.mjs +131 -0
  86. package/plugins/dsh/skills/reinstall-xp-gate/tests/util.test.mjs +154 -0
  87. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  88. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  89. package/plugins/opencode/package.json +1 -1
  90. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  91. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  92. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  93. package/plugins/qoder/plugin.json +1 -1
  94. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  95. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  96. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  97. package/principles/adapters/function-body.ts +60 -0
  98. package/principles/adapters/typescript.ts +54 -4
  99. package/principles/config.ts +16 -3
  100. package/scripts/delphi-repo-tools.cjs +4 -1
  101. package/skills/delphi-review/AGENTS.md +1 -1
  102. package/skills/sprint-flow/AGENTS.md +1 -1
  103. package/skills/test-specification-alignment/AGENTS.md +1 -1
@@ -0,0 +1,255 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import path from 'node:path';
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+
7
+ import {
8
+ HOME, effectivePath, envWithPath, firstExisting, isWindowsShim, npmCli, packageDir, probe,
9
+ resetPackageDir, run, withPlatform, parseWhichOutput, PROBE_TIMEOUT_MS,
10
+ } from '../scripts/lib/proc.mjs';
11
+ import { isFile } from '../scripts/lib/util.mjs';
12
+
13
+ test('HOME is an absolute path', () => {
14
+ assert.equal(typeof HOME, 'string');
15
+ assert.ok(path.isAbsolute(HOME), `HOME must be absolute, got: ${HOME}`);
16
+ });
17
+
18
+ test('effectivePath is non-empty, deduplicated and contains the node dir', () => {
19
+ const parts = effectivePath().split(path.delimiter).filter(Boolean);
20
+
21
+ assert.ok(parts.length > 0);
22
+ assert.ok(parts.includes(path.dirname(process.execPath)), 'node dir must be reachable');
23
+ assert.equal(new Set(parts).size, parts.length);
24
+ });
25
+
26
+ test('effectivePath keeps the caller PATH order on POSIX', () => {
27
+ // Prepending the node dir unconditionally put /usr/bin first on Linux, so a tool
28
+ // installed earlier in PATH was shadowed by a stale /usr/bin copy: jq resolved
29
+ // to 1.6 while `~/.local/bin/jq` was 1.8.2, and the report called it outdated.
30
+ // Only Windows needs the prefix (npm .cmd shims call bare `node`).
31
+ const first = effectivePath().split(path.delimiter).filter(Boolean)[0];
32
+ if (process.platform === 'win32') {
33
+ assert.equal(first, path.dirname(process.execPath));
34
+ return;
35
+ }
36
+ const expected = (process.env.PATH || '').split(path.delimiter).filter(Boolean)[0];
37
+ assert.equal(first, expected, 'the caller PATH order must not be rewritten on POSIX');
38
+ });
39
+
40
+ test('effectivePath is cached and returns the identical string', () => {
41
+ assert.equal(effectivePath(), effectivePath());
42
+ });
43
+
44
+ test('envWithPath copies the environment and overrides PATH', () => {
45
+ const env = envWithPath();
46
+ assert.equal(env.PATH, effectivePath());
47
+ // A copy, not the live process.env object -- mutating it must not leak.
48
+ assert.notEqual(env, process.env);
49
+ });
50
+
51
+ test('run executes a real command and reports its exit status', () => {
52
+ const r = run(process.execPath, ['-e', 'process.stdout.write("ok")']);
53
+ assert.equal(r.status, 0);
54
+ assert.equal(String(r.stdout).trim(), 'ok');
55
+ });
56
+
57
+ test('run captures a non-zero exit instead of throwing', () => {
58
+ assert.equal(run(process.execPath, ['-e', 'process.exit(3)']).status, 3);
59
+ });
60
+
61
+ test('run honours the timeout option', () => {
62
+ // A hung gate tool must not hang the whole reinstall; it becomes a failed run.
63
+ const r = run(process.execPath, ['-e', 'setTimeout(()=>{}, 5000)'], { timeout: 50 });
64
+ assert.notEqual(r.status, 0);
65
+ });
66
+
67
+ test('npmCli resolves to an existing npm-cli.js next to node', () => {
68
+ const cli = npmCli();
69
+ // Empty means runNpm degrades to status 127.
70
+ if (cli) assert.ok(isFile(cli), `resolved npmCli does not exist: ${cli}`);
71
+ });
72
+
73
+ test('packageDir honours XP_GATE_PACKAGE_DIR', () => {
74
+ const original = process.env.XP_GATE_PACKAGE_DIR;
75
+ try {
76
+ process.env.XP_GATE_PACKAGE_DIR = process.cwd();
77
+ resetPackageDir();
78
+ // The override lets a test or sandbox pin the package location.
79
+ assert.equal(packageDir(), process.cwd());
80
+ } finally {
81
+ if (original === undefined) delete process.env.XP_GATE_PACKAGE_DIR;
82
+ else process.env.XP_GATE_PACKAGE_DIR = original;
83
+ resetPackageDir();
84
+ }
85
+ assert.equal(typeof packageDir(), 'string');
86
+ });
87
+
88
+ test('resetPackageDir clears the memoised value without changing the answer', () => {
89
+ const first = packageDir();
90
+ resetPackageDir();
91
+ assert.equal(first, packageDir());
92
+ });
93
+
94
+ // ---------------------------------------------------------------------------
95
+ // Platform injection (TODO-3 / WSL migration).
96
+ //
97
+ // process.platform is frozen at startup, so every Windows branch in proc.mjs was
98
+ // unreachable on Linux and untestable on Windows. After migrating the dev box to
99
+ // WSL the Windows code would have quietly lost its only coverage. `withPlatform`
100
+ // makes the decision an argument so both branches are testable from either OS.
101
+ //
102
+ // The rule this encodes: the injected value decides the branch, and the real
103
+ // process.platform is the default.
104
+ // ---------------------------------------------------------------------------
105
+
106
+ test('withPlatform runs the callback with the platform it was given', () => {
107
+ const seen = withPlatform('win32', () => process.platform);
108
+ assert.equal(seen, 'win32', 'the injected platform must be visible to the callback');
109
+ });
110
+
111
+ test('withPlatform restores the real platform afterwards, even when the callback throws', () => {
112
+ const real = process.platform;
113
+ assert.throws(() => withPlatform('win32', () => { throw new Error('boom'); }), /boom/);
114
+ assert.equal(process.platform, real, 'a throwing callback must not leak the fake platform');
115
+ });
116
+
117
+ test('withPlatform returns whatever the callback returns', () => {
118
+ assert.equal(withPlatform('linux', () => 42), 42);
119
+ });
120
+
121
+ test('isWindowsShim recognises .cmd and .bat only on win32', () => {
122
+ // npm on Windows installs a .cmd shim, which needs cmd.exe; a .cmd path on
123
+ // Linux is just an odd filename and must not trigger the comspec branch.
124
+ withPlatform('win32', () => {
125
+ assert.equal(isWindowsShim('C:\\npm\\jscpd.cmd'), true);
126
+ assert.equal(isWindowsShim('C:\\npm\\jscpd.CMD'), true, 'the check is case-insensitive');
127
+ assert.equal(isWindowsShim('C:\\npm\\jscpd.bat'), true);
128
+ });
129
+ withPlatform('linux', () => {
130
+ assert.equal(isWindowsShim('/usr/local/bin/jscpd'), false);
131
+ assert.equal(isWindowsShim('/home/u/jscpd.cmd'), false, 'extension alone is not enough off Windows');
132
+ });
133
+ });
134
+
135
+ test('firstExisting accepts the bare path on any platform', () => {
136
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'xgr-first-'));
137
+ try {
138
+ const bare = path.join(dir, 'tool');
139
+ fs.writeFileSync(bare, '');
140
+ assert.equal(firstExisting(bare), bare);
141
+ } finally {
142
+ fs.rmSync(dir, { recursive: true, force: true });
143
+ }
144
+ });
145
+
146
+ test('firstExisting appends PATHEXT-style extensions only on win32', () => {
147
+ // The Windows failure this models: `where jscpd` lists the extensionless shell
148
+ // shim FIRST, and spawnSync of that shim returns ENOENT even though jscpd.exe
149
+ // sits right beside it.
150
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'xgr-first-'));
151
+ try {
152
+ const base = path.join(dir, 'tool');
153
+ fs.writeFileSync(`${base}.exe`, '');
154
+ assert.equal(firstExisting(base), '', 'off Windows an absent bare path is simply absent');
155
+ assert.equal(
156
+ withPlatform('win32', () => firstExisting(base)),
157
+ `${base}.exe`,
158
+ 'on win32 the .exe beside it is the real executable',
159
+ );
160
+ } finally {
161
+ fs.rmSync(dir, { recursive: true, force: true });
162
+ }
163
+ });
164
+
165
+ test('probe routes a .cmd shim through cmd.exe on win32 instead of spawning it directly', () => {
166
+ // Measured failure this models: spawnSync of a .cmd without a shell returns
167
+ // EINVAL on Windows, so the gate reports "tool installed but produced no
168
+ // output". The routed call must therefore name cmd.exe, and the shim must
169
+ // arrive quoted with windowsVerbatimArguments so backslashes survive.
170
+ const shim = path.join(os.tmpdir(), 'fake-tool.cmd');
171
+ const r = withPlatform('win32', () => probe(shim, ['--version'], {
172
+ env: { ComSpec: '/bin/echo' },
173
+ }));
174
+ // /bin/echo stands in for cmd.exe: whatever it echoes is the command line
175
+ // that would have been handed to the shell.
176
+ const line = String(r.stdout);
177
+ assert.match(line, /fake-tool\.cmd/, 'the shim must be the program being run');
178
+ assert.match(line, /--version/, 'the arguments must be forwarded');
179
+ });
180
+
181
+ test('probe spawns a plain executable directly on win32, without a shell', () => {
182
+ // The comspec route is for shims only; an .exe must not be wrapped in cmd.exe,
183
+ // which would break exit codes and quoting for every real tool.
184
+ const r = withPlatform('win32', () => probe(process.execPath, ['-e', 'process.stdout.write("direct")']));
185
+ assert.equal(r.status, 0);
186
+ assert.equal(String(r.stdout), 'direct');
187
+ });
188
+
189
+ test('probe on linux never takes the comspec route, even for a .cmd path', () => {
190
+ // /bin/sh is the stand-in: if the comspec branch ran, the output would be the
191
+ // echoed command line rather than the tool's own error.
192
+ const r = withPlatform('linux', () => probe('/nonexistent/tool.cmd', [], { env: { ComSpec: '/bin/echo' } }));
193
+ assert.doesNotMatch(String(r.stdout || ''), /nonexistent\/tool\.cmd/);
194
+ assert.notEqual(r.status, 0, 'a missing program must fail rather than fake success');
195
+ });
196
+
197
+ test('parseWhichOutput picks the first runnable path from where output on win32', () => {
198
+ // Measured on the Windows box: `where jscpd` listed an extensionless shell
199
+ // shim BEFORE jscpd.cmd, and spawnSync of that shim returns ENOENT -- the tool
200
+ // was installed but unreachable. The parser must skip anything that is not a
201
+ // real file and keep looking, rather than trusting the first line.
202
+ const out = ['C:\\npm\\jscpd', 'C:\\npm\\jscpd.cmd'].join('\r\n');
203
+ const resolved = withPlatform('win32', () => parseWhichOutput(out, () => 'C:\\npm\\jscpd'));
204
+ assert.equal(resolved, 'C:\\npm\\jscpd', 'a resolvable first line is returned as-is');
205
+ });
206
+
207
+ test('parseWhichOutput skips entries that do not exist and falls through', () => {
208
+ // Built on real files: `firstExisting` must be the code under test, not a stub
209
+ // that returns the hit path (which `.find(Boolean)` would reduce to `true`).
210
+ // The first line is a path that does not exist; the second is a real file.
211
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'xgr-which-'));
212
+ try {
213
+ const real = path.join(dir, 'tool');
214
+ fs.writeFileSync(real, '');
215
+ const out = `${path.join(dir, 'missing')}\n${real}\n`;
216
+ assert.equal(withPlatform('win32', () => parseWhichOutput(out)), real);
217
+ } finally {
218
+ fs.rmSync(dir, { recursive: true, force: true });
219
+ }
220
+ });
221
+
222
+ test('parseWhichOutput returns empty when where found nothing runnable', () => {
223
+ assert.equal(withPlatform('win32', () => parseWhichOutput('', () => '')), '');
224
+ assert.equal(withPlatform('win32', () => parseWhichOutput('\r\n\r\n', () => '')), '');
225
+ });
226
+
227
+ test('parseWhichOutput ignores carriage returns in where output', () => {
228
+ // cmd.exe emits CRLF; a parser splitting on "\n" alone would keep a trailing \r
229
+ // in the path and produce a path that does not exist.
230
+ const out = 'C:\\a\\tool.exe\r\n';
231
+ assert.equal(withPlatform('win32', () => parseWhichOutput('C:\\a\\tool.exe\r\n', (p) => p)), 'C:\\a\\tool.exe');
232
+ });
233
+
234
+ // ---------------------------------------------------------------------------
235
+ // Timeout budgets (magic-number refactor).
236
+ //
237
+ // These are values, not behaviour, and nothing above pins them: a refactor that
238
+ // silently turned 10s into 30s would still pass every other test in this file.
239
+ // The budgets are named by INTENT, not by duration, because three groups of
240
+ // equal numbers existed only by coincidence -- `npm root -g` and a node syntax
241
+ // check both got 30s for unrelated reasons and must be free to diverge.
242
+ // ---------------------------------------------------------------------------
243
+
244
+ test('PROBE_TIMEOUT_MS is a short budget for commands that must answer fast', () => {
245
+ // which/where/registry queries. If one of these hangs, the tool is unusable
246
+ // and a long wait only delays the report.
247
+ assert.equal(PROBE_TIMEOUT_MS, 10000);
248
+ });
249
+
250
+ test('probe-tier lookups actually use PROBE_TIMEOUT_MS', () => {
251
+ // The constant is worthless if the call sites kept their own literals.
252
+ const src = fs.readFileSync(new URL('../scripts/lib/proc.mjs', import.meta.url), 'utf8');
253
+ const probeCalls = src.match(/timeout: 10000\b/g) || [];
254
+ assert.deepEqual(probeCalls, [], 'probe-tier call sites must reference PROBE_TIMEOUT_MS, not 10000');
255
+ });
@@ -0,0 +1,66 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+
4
+ import { table, section, item, note, MARK } from '../scripts/lib/report.mjs';
5
+
6
+ /** Capture everything a reporter function writes to stdout. */
7
+ function capture(fn) {
8
+ const lines = [];
9
+ const original = console.log;
10
+ console.log = (...args) => lines.push(args.join(' '));
11
+ try {
12
+ fn();
13
+ } finally {
14
+ console.log = original;
15
+ }
16
+ return lines;
17
+ }
18
+
19
+ test('MARK exposes every status the report renders', () => {
20
+ for (const key of ['PASS', 'WARN', 'FAIL', 'SKIP', 'INFO']) {
21
+ assert.equal(typeof MARK[key], 'string');
22
+ assert.ok(MARK[key].length > 0);
23
+ }
24
+ });
25
+
26
+ test('section and item format exactly one line each', () => {
27
+ assert.deepEqual(capture(() => section('Title')), ['\n=== Title ===']);
28
+ assert.deepEqual(capture(() => item(MARK.PASS, 'all good')), [' [PASS] all good']);
29
+ assert.deepEqual(capture(() => note('detail')), [' detail']);
30
+ });
31
+
32
+ test('table pads every column to the widest cell', () => {
33
+ const lines = capture(() => table(['a', 'bb'], [['xx', 'y'], ['z', 'zzz']]));
34
+ assert.equal(lines.length, 4);
35
+
36
+ const sep = lines[1].replace(/^ {2}/, '');
37
+ const parts = sep.split(' ');
38
+ // Widest cell per column: "a"/"xx"/"z" -> 2, "bb"/"y"/"zzz" -> 3.
39
+ assert.equal(parts[0].length, 2);
40
+ assert.equal(parts[1].length, 3);
41
+
42
+ // Every data row must start its cells at the same offsets, or the table
43
+ // renders misaligned -- the one job this helper has.
44
+ for (const line of [lines[0], lines[2], lines[3]]) {
45
+ const body = line.replace(/^ {2}/, '');
46
+ assert.ok(body.slice(0, 2).trim().length > 0);
47
+ assert.equal(body.slice(2, 4), ' ');
48
+ }
49
+ });
50
+
51
+ test('table renders null and undefined cells as empty, not "null"', () => {
52
+ const lines = capture(() => table(['h'], [[null], [undefined], [0]]));
53
+ assert.ok(!lines.some((l) => l.includes('null') || l.includes('undefined')));
54
+ // 0 must still render; only null/undefined become blank.
55
+ assert.ok(lines.some((l) => l.trim() === '0'));
56
+ });
57
+
58
+ test('table handles a headers-only call without throwing', () => {
59
+ assert.equal(capture(() => table(['only'], [])).length, 2);
60
+ });
61
+
62
+ test('table with a single column does not emit undefined', () => {
63
+ const lines = capture(() => table(['x'], [['1'], ['22']]));
64
+ assert.equal(lines.length, 4);
65
+ assert.ok(lines.every((l) => !l.includes('undefined')));
66
+ });
@@ -0,0 +1,278 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ import {
7
+ backupThenRemove, hasXpGateMarker, scanSkillResidue, pruneDeadRoots,
8
+ contentHashes, MARKER_SCAN_LIMIT, sweepLegacySelfCopy,
9
+ } from '../scripts/lib/residue.mjs';
10
+ import { hashTree, isFile } from '../scripts/lib/util.mjs';
11
+ import { tmpDir, fakePkg, deploySkill, editSkill } from './fixtures.mjs';
12
+
13
+ /** Stand-in for a user-edited SKILL.md; must differ from the bundled one. */
14
+ const USER_EDIT = '# edited by the user\n';
15
+
16
+ // --- backupThenRemove: every call in reinstall deletes user data ------------
17
+
18
+ test('backupThenRemove copies a directory into residue/ then deletes the original', (t) => {
19
+ const runDir = tmpDir(t);
20
+ const victim = tmpDir(t);
21
+ fs.writeFileSync(path.join(victim, 'a.txt'), 'important');
22
+ fs.mkdirSync(path.join(victim, 'nested'));
23
+ fs.writeFileSync(path.join(victim, 'nested', 'b.txt'), 'deep');
24
+
25
+ backupThenRemove(victim, runDir, path.join('skills', 'DSH-thing'));
26
+
27
+ assert.equal(fs.existsSync(victim), false, 'original must be gone');
28
+ const backup = path.join(runDir, 'residue', 'skills', 'DSH-thing');
29
+ assert.equal(fs.readFileSync(path.join(backup, 'a.txt'), 'utf8'), 'important');
30
+ assert.equal(fs.readFileSync(path.join(backup, 'nested', 'b.txt'), 'utf8'), 'deep');
31
+ });
32
+
33
+ test('backupThenRemove handles a single file entry', (t) => {
34
+ const runDir = tmpDir(t);
35
+ const victim = tmpDir(t);
36
+ const file = path.join(victim, 'pre-commit');
37
+ fs.writeFileSync(file, '#!/bin/sh\n# xp-gate');
38
+
39
+ backupThenRemove(file, runDir, path.join('project-hooks', 'pre-commit'), true);
40
+
41
+ assert.equal(fs.existsSync(file), false);
42
+ assert.equal(
43
+ fs.readFileSync(path.join(runDir, 'residue', 'project-hooks', 'pre-commit'), 'utf8'),
44
+ '#!/bin/sh\n# xp-gate'
45
+ );
46
+ });
47
+
48
+ test('backupThenRemove creates nested label directories', (t) => {
49
+ const runDir = tmpDir(t);
50
+ const victim = tmpDir(t);
51
+ fs.writeFileSync(path.join(victim, 'f'), 'x');
52
+
53
+ // Labels like "templates/<agent>/git-hooks-template" are three levels deep.
54
+ assert.doesNotThrow(() => backupThenRemove(victim, runDir, 'templates/Qoder/git-hooks-template'));
55
+ assert.ok(isFile(path.join(runDir, 'residue', 'templates', 'Qoder', 'git-hooks-template', 'f')));
56
+ });
57
+
58
+ // --- hasXpGateMarker: guards against deleting unrelated directories --------
59
+
60
+ test('hasXpGateMarker finds the marker in a nested file', (t) => {
61
+ const dir = tmpDir(t);
62
+ fs.mkdirSync(path.join(dir, 'hooks'));
63
+ fs.writeFileSync(path.join(dir, 'hooks', 'pre-commit'), '#!/bin/sh\n# generated by xp-gate\n');
64
+
65
+ assert.equal(hasXpGateMarker(dir), true);
66
+ });
67
+
68
+ test('hasXpGateMarker matches case-insensitively', (t) => {
69
+ const dir = tmpDir(t);
70
+ fs.writeFileSync(path.join(dir, 'f'), 'XP-GATE');
71
+
72
+ assert.equal(hasXpGateMarker(dir), true);
73
+ });
74
+
75
+ test('hasXpGateMarker returns false for an unrelated directory', (t) => {
76
+ const dir = tmpDir(t);
77
+ fs.writeFileSync(path.join(dir, 'mine.sh'), 'echo hello\n');
78
+
79
+ // This is the whole safety property: no marker means do NOT delete.
80
+ assert.equal(hasXpGateMarker(dir), false);
81
+ });
82
+
83
+ test('hasXpGateMarker returns false for an empty or missing directory', (t) => {
84
+ const dir = tmpDir(t);
85
+ assert.equal(hasXpGateMarker(dir), false);
86
+ assert.equal(hasXpGateMarker('/no/such/dir'), false);
87
+ });
88
+
89
+ test('hasXpGateMarker tolerates binary files without throwing', (t) => {
90
+ const dir = tmpDir(t);
91
+ fs.writeFileSync(path.join(dir, 'binary.bin'), Buffer.from([0x00, 0xff, 0xfe]));
92
+ fs.writeFileSync(path.join(dir, 'note.md'), 'xp-gate');
93
+
94
+ assert.equal(hasXpGateMarker(dir), true);
95
+ });
96
+
97
+ test('hasXpGateMarker caps how many files it inspects', (t) => {
98
+ const dir = tmpDir(t);
99
+ // Marker sits beyond the cap; the bounded scan must return false rather than
100
+ // walking an unbounded tree.
101
+ for (let i = 0; i < MARKER_SCAN_LIMIT + 5; i += 1) {
102
+ fs.writeFileSync(path.join(dir, `f${String(i).padStart(3, '0')}.txt`), 'plain');
103
+ }
104
+ fs.writeFileSync(path.join(dir, 'zzz-last.txt'), 'xp-gate');
105
+
106
+ assert.equal(hasXpGateMarker(dir), false);
107
+ });
108
+
109
+ // --- scanSkillResidue: decides what is safe to delete ----------------------
110
+
111
+ test('scanSkillResidue separates byte-identical copies from user-modified ones', (t) => {
112
+ const pkg = fakePkg(t, ['alpha']);
113
+ const root = tmpDir(t);
114
+ const srcHash = hashTree(path.join(pkg, 'skills', 'alpha'));
115
+
116
+ deploySkill(pkg, root, 'alpha');
117
+ editSkill(deploySkill(pkg, root, 'alpha', 'beta'), '# edited\n');
118
+
119
+ const oldHashes = new Map([['alpha', srcHash], ['beta', srcHash]]);
120
+ const { identical, modified } = scanSkillResidue([{ agent: 'A', dir: root }], oldHashes);
121
+
122
+ assert.deepEqual(identical.map((r) => r.name), ['alpha']);
123
+ assert.deepEqual(modified.map((r) => r.name), ['beta']);
124
+ });
125
+
126
+ test('scanSkillResidue ignores directories that are not in the old package', (t) => {
127
+ const root = tmpDir(t);
128
+ fs.mkdirSync(path.join(root, 'unrelated'));
129
+ fs.writeFileSync(path.join(root, 'unrelated', 'x'), 'y');
130
+
131
+ const { identical, modified } = scanSkillResidue([{ agent: 'A', dir: root }], new Map());
132
+ assert.deepEqual(identical, []);
133
+ assert.deepEqual(modified, []);
134
+ });
135
+
136
+ test('scanSkillResidue skips unreadable roots', () => {
137
+ const result = scanSkillResidue([{ agent: 'A', dir: '/no/such/root' }], new Map([['alpha', 'deadbeef']]));
138
+ assert.deepEqual(result, { identical: [], modified: [] });
139
+ });
140
+
141
+ // --- pruneDeadRoots: deletes only exact matches ----------------------------
142
+
143
+ test('pruneDeadRoots deletes byte-identical copies but spares edited ones', (t) => {
144
+ // Two dead agent roots each holding the SAME skill name: one untouched, one
145
+ // edited by the user. This is the exact case the hash comparison exists for.
146
+ // Naming the edited copy something else would make this pass for the wrong
147
+ // reason -- contentHashes() only iterates names present in the package, so a
148
+ // differently-named dir is skipped before any hash is ever computed.
149
+ const pkg = fakePkg(t, ['alpha']);
150
+ const untouched = tmpDir(t);
151
+ const edited = tmpDir(t);
152
+
153
+ deploySkill(pkg, untouched, 'alpha');
154
+ editSkill(deploySkill(pkg, edited, 'alpha'), USER_EDIT);
155
+
156
+ const removed = pruneDeadRoots(pkg, [
157
+ { agent: 'Untouched', dir: untouched },
158
+ { agent: 'Edited', dir: edited },
159
+ ]);
160
+
161
+ assert.equal(removed, 1);
162
+ assert.equal(fs.existsSync(path.join(untouched, 'alpha')), false, 'identical copy must go');
163
+ // Dropping the hash check deletes this too -- silent data loss.
164
+ assert.equal(fs.existsSync(path.join(edited, 'alpha')), true, 'edited copy is user data');
165
+ assert.equal(fs.readFileSync(path.join(edited, 'alpha', 'SKILL.md'), 'utf8'), USER_EDIT);
166
+ });
167
+
168
+ /** What install.mjs actually writes: the whole tree, front matter included. */
169
+ const SELF_SKILL_MD = ['---', 'name: xp-gate-reinstall', 'version: 1.3.3', '---', '', '# self', ''].join('\n');
170
+
171
+ /** An agent root holding a pre-2.0.0 self copy. */
172
+ function legacySelfRoot(t, contents = SELF_SKILL_MD) {
173
+ const root = tmpDir(t);
174
+ const legacy = path.join(root, 'xp-gate-reinstall');
175
+ fs.mkdirSync(legacy);
176
+ fs.writeFileSync(path.join(legacy, 'SKILL.md'), contents);
177
+ return { root, legacy };
178
+ }
179
+
180
+ test('pruneDeadRoots also removes a stray copy under the OLD skill name', (t) => {
181
+ // The skill was renamed xp-gate-reinstall -> reinstall-xp-gate in 2.0.0. Every
182
+ // machine that ran the old installer has a copy under the old name in each
183
+ // agent root. Nothing would ever update that copy again -- the package ships
184
+ // nothing under that name any more -- so it has to be swept automatically, or
185
+ // a fleet of stale skills accumulates.
186
+ const pkg = fakePkg(t, ['alpha']);
187
+ const { root, legacy } = legacySelfRoot(t);
188
+
189
+ assert.equal(pruneDeadRoots(pkg, [{ agent: 'A', dir: root }]), 1);
190
+ assert.equal(fs.existsSync(legacy), false, 'legacy copy must be swept');
191
+ });
192
+
193
+ test('pruneDeadRoots leaves an EDITED legacy copy alone', (t) => {
194
+ // Same rule as every other skill here: an exact copy of ours is ours to
195
+ // delete, an edited one is user data. The rename must not become a licence to
196
+ // delete whatever happens to sit under the old name.
197
+ const pkg = fakePkg(t, ['alpha']);
198
+ const { root, legacy } = legacySelfRoot(t, `${USER_EDIT}\n`);
199
+
200
+ pruneDeadRoots(pkg, [{ agent: 'A', dir: root }]);
201
+
202
+ assert.equal(fs.existsSync(legacy), true, 'an edited legacy copy is user data');
203
+ });
204
+
205
+ test('a copy is only ours when its name: line matches exactly', (t) => {
206
+ // The marker decides whether a directory may be deleted. A substring or
207
+ // prefix match would let `name: reinstall-xp-gate-fork` be swept as ours, so
208
+ // the comparison is exact on both names.
209
+ const { root } = legacySelfRoot(t, ['---', 'name: reinstall-xp-gate-fork', '---', ''].join('\n'));
210
+
211
+ assert.equal(sweepLegacySelfCopy(root), 0, 'a fork is not ours');
212
+ assert.equal(fs.existsSync(path.join(root, 'xp-gate-reinstall')), true);
213
+ });
214
+
215
+ test('pruneDeadRoots does nothing when the package has no skills', (t) => {
216
+ const root = tmpDir(t);
217
+ const pkg = tmpDir(t, 'xgr-empty-pkg-');
218
+
219
+ assert.equal(pruneDeadRoots(pkg, [{ agent: 'A', dir: root }]), 0);
220
+ });
221
+
222
+ test('pruneDeadRoots never touches unrelated directories', (t) => {
223
+ const pkg = fakePkg(t, ['alpha']);
224
+ const root = tmpDir(t);
225
+ fs.mkdirSync(path.join(root, 'my-own-skill'));
226
+ fs.writeFileSync(path.join(root, 'my-own-skill', 'SKILL.md'), '# mine\n');
227
+
228
+ pruneDeadRoots(pkg, [{ agent: 'A', dir: root }]);
229
+
230
+ assert.equal(fs.existsSync(path.join(root, 'my-own-skill')), true);
231
+ });
232
+
233
+ // --- contentHashes --------------------------------------------------------
234
+
235
+ test('contentHashes maps skill names to directory hashes', (t) => {
236
+ const pkg = fakePkg(t, ['alpha', 'beta']);
237
+ const hashes = contentHashes(pkg);
238
+
239
+ assert.deepEqual([...hashes.keys()].sort(), ['alpha', 'beta']);
240
+ assert.match(hashes.get('alpha'), /^[a-f0-9]{64}$/);
241
+ });
242
+
243
+ test('contentHashes returns an empty map for a package without skills/', (t) => {
244
+ assert.equal(contentHashes(tmpDir(t)).size, 0);
245
+ assert.equal(contentHashes('/no/such/pkg').size, 0);
246
+ });
247
+
248
+ test('sweepLegacySelfCopy clears the old name in a LIVE agent root too', (t) => {
249
+ // pruneDeadRoots only ever sees agents judged dead. The rename has to reach
250
+ // every root that is still in use as well -- measured during the real 2.0.0
251
+ // install: six new copies were written and all five old ones stayed behind,
252
+ // because nothing in install.mjs looked at the legacy name at all.
253
+ const { root, legacy } = legacySelfRoot(t);
254
+
255
+ const removed = sweepLegacySelfCopy(root);
256
+
257
+ assert.equal(removed, 1);
258
+ assert.equal(fs.existsSync(legacy), false);
259
+ });
260
+
261
+ test('sweepLegacySelfCopy leaves an edited legacy copy alone', (t) => {
262
+ const { root, legacy } = legacySelfRoot(t, `${USER_EDIT}\n`);
263
+
264
+ assert.equal(sweepLegacySelfCopy(root), 0);
265
+ assert.equal(fs.existsSync(legacy), true);
266
+ });
267
+
268
+ test('sweepLegacySelfCopy never touches the current name', (t) => {
269
+ // The sweep runs from install.mjs right after the current copy is written;
270
+ // deleting that would undo the install it is part of.
271
+ const root = tmpDir(t);
272
+ const current = path.join(root, 'reinstall-xp-gate');
273
+ fs.mkdirSync(current);
274
+ fs.writeFileSync(path.join(current, 'SKILL.md'), SELF_SKILL_MD.replace('xp-gate-reinstall', 'reinstall-xp-gate'));
275
+
276
+ assert.equal(sweepLegacySelfCopy(root), 0);
277
+ assert.equal(fs.existsSync(current), true);
278
+ });
@@ -0,0 +1,70 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ import { newerSkillDir } from '../scripts/lib/selfsync.mjs';
8
+
9
+ /**
10
+ * Which tree install.mjs treats as the source of truth.
11
+ *
12
+ * MEASURED on the 2.0.1 release: the repo was at 2.0.1, the canonical copy
13
+ * under ~/.local/share/xp-gate/skills/ was still 2.0.0, and `install.mjs`
14
+ * reported "已写入 0 个副本". defaultSource() returns the canonical dir
15
+ * whenever it exists, so a newer checkout can never update the copies it
16
+ * installed -- the release does not propagate. The newer tree must win.
17
+ */
18
+
19
+ function tree(version) {
20
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'xgr-src-'));
21
+ fs.writeFileSync(path.join(dir, 'SKILL.md'), '---\nname: reinstall-xp-gate\n---\n');
22
+ if (version !== null) fs.writeFileSync(path.join(dir, 'VERSION'), `${version}\n`);
23
+ return dir;
24
+ }
25
+
26
+ test('newerSkillDir picks the tree with the higher VERSION', () => {
27
+ const older = tree('2.0.0');
28
+ const newer = tree('2.0.1');
29
+ try {
30
+ assert.equal(newerSkillDir(older, newer), newer);
31
+ assert.equal(newerSkillDir(newer, older), newer);
32
+ } finally {
33
+ fs.rmSync(older, { recursive: true, force: true });
34
+ fs.rmSync(newer, { recursive: true, force: true });
35
+ }
36
+ });
37
+
38
+ test('newerSkillDir keeps the first tree when the versions match', () => {
39
+ const a = tree('2.0.1');
40
+ const b = tree('2.0.1');
41
+ try {
42
+ assert.equal(newerSkillDir(a, b), a);
43
+ } finally {
44
+ fs.rmSync(a, { recursive: true, force: true });
45
+ fs.rmSync(b, { recursive: true, force: true });
46
+ }
47
+ });
48
+
49
+ test('newerSkillDir ignores a candidate that is not a skill tree', () => {
50
+ const skill = tree('2.0.1');
51
+ const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'xgr-src-'));
52
+ try {
53
+ assert.equal(newerSkillDir(skill, empty), skill);
54
+ assert.equal(newerSkillDir(empty, skill), skill);
55
+ } finally {
56
+ fs.rmSync(skill, { recursive: true, force: true });
57
+ fs.rmSync(empty, { recursive: true, force: true });
58
+ }
59
+ });
60
+
61
+ test('newerSkillDir treats a missing VERSION as older than any real one', () => {
62
+ const unversioned = tree(null);
63
+ const versioned = tree('2.0.1');
64
+ try {
65
+ assert.equal(newerSkillDir(unversioned, versioned), versioned);
66
+ } finally {
67
+ fs.rmSync(unversioned, { recursive: true, force: true });
68
+ fs.rmSync(versioned, { recursive: true, force: true });
69
+ }
70
+ });