@opengsd/gsd-core 1.3.1 → 1.4.0-rc.2

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 (136) hide show
  1. package/.claude-plugin/plugin.json +23 -0
  2. package/GEMINI.md +53 -0
  3. package/agents/gsd-advisor-researcher.md +1 -20
  4. package/agents/gsd-ai-researcher.md +2 -21
  5. package/agents/gsd-code-fixer.md +1 -1
  6. package/agents/gsd-code-reviewer.md +1 -1
  7. package/agents/gsd-domain-researcher.md +2 -21
  8. package/agents/gsd-eval-auditor.md +1 -1
  9. package/agents/gsd-eval-planner.md +1 -1
  10. package/agents/gsd-executor.md +1 -1
  11. package/agents/gsd-framework-selector.md +1 -1
  12. package/agents/gsd-nyquist-auditor.md +1 -1
  13. package/agents/gsd-pattern-mapper.md +1 -1
  14. package/agents/gsd-phase-researcher.md +92 -166
  15. package/agents/gsd-planner.md +9 -36
  16. package/agents/gsd-project-researcher.md +62 -141
  17. package/agents/gsd-security-auditor.md +1 -1
  18. package/agents/gsd-ui-auditor.md +1 -1
  19. package/agents/gsd-ui-checker.md +1 -1
  20. package/agents/gsd-ui-researcher.md +3 -22
  21. package/agents/gsd-user-profiler.md +1 -1
  22. package/agents/gsd-verifier.md +8 -2
  23. package/bin/install.js +1977 -339
  24. package/commands/gsd/autonomous.md +2 -0
  25. package/commands/gsd/execute-phase.md +2 -0
  26. package/commands/gsd/graphify.md +11 -6
  27. package/commands/gsd/import.md +6 -2
  28. package/commands/gsd/plan-phase.md +4 -2
  29. package/commands/gsd/progress.md +1 -0
  30. package/commands/gsd/stats.md +1 -0
  31. package/commands/gsd/update.md +3 -2
  32. package/gemini-extension.json +6 -0
  33. package/gsd-core/bin/check-latest-version.cjs +61 -6
  34. package/gsd-core/bin/gsd-tools.cjs +238 -32
  35. package/gsd-core/bin/lib/check-command-router.cjs +1 -0
  36. package/gsd-core/bin/lib/cli-exit.cjs +42 -0
  37. package/gsd-core/bin/lib/command-routing-hub.cjs +1 -1
  38. package/gsd-core/bin/lib/commands.cjs +5 -4
  39. package/gsd-core/bin/lib/config.cjs +28 -4
  40. package/gsd-core/bin/lib/core.cjs +72 -28
  41. package/gsd-core/bin/lib/graphify.cjs +2 -2
  42. package/gsd-core/bin/lib/init-command-router.cjs +2 -2
  43. package/gsd-core/bin/lib/init.cjs +19 -3
  44. package/gsd-core/bin/lib/install-profiles.cjs +58 -0
  45. package/gsd-core/bin/lib/installer-migration-report.cjs +3 -0
  46. package/gsd-core/bin/lib/installer-migrations/000-first-time-baseline.cjs +1 -1
  47. package/gsd-core/bin/lib/intel.cjs +3 -20
  48. package/gsd-core/bin/lib/package-legitimacy.cjs +368 -0
  49. package/gsd-core/bin/lib/phase.cjs +3 -3
  50. package/gsd-core/bin/lib/research-provider.cjs +137 -0
  51. package/gsd-core/bin/lib/research-store.cjs +167 -0
  52. package/gsd-core/bin/lib/roadmap-upgrade.cjs +4 -19
  53. package/gsd-core/bin/lib/runtime-artifact-layout.cjs +67 -9
  54. package/gsd-core/bin/lib/runtime-config-adapter-registry.cjs +56 -0
  55. package/gsd-core/bin/lib/runtime-homes.cjs +32 -11
  56. package/gsd-core/bin/lib/security.cjs +73 -0
  57. package/gsd-core/bin/lib/shell-command-projection.cjs +9 -0
  58. package/gsd-core/bin/lib/surface.cjs +54 -11
  59. package/gsd-core/bin/lib/validate.cjs +2 -2
  60. package/gsd-core/bin/lib/verification-command-router.cjs +31 -0
  61. package/gsd-core/bin/lib/verification.cjs +193 -0
  62. package/gsd-core/bin/lib/verify.cjs +2 -2
  63. package/gsd-core/bin/lib/workstream-inventory.cjs +1 -1
  64. package/gsd-core/bin/lib/worktree-base-ref.cjs +325 -0
  65. package/gsd-core/bin/lib/worktree-safety.cjs +31 -0
  66. package/gsd-core/bin/shared/config-schema.manifest.json +2 -1
  67. package/gsd-core/bin/verify-reapply-patches.cjs +8 -11
  68. package/gsd-core/references/planner-load-graph-context.md +36 -0
  69. package/gsd-core/references/planning-config.md +3 -1
  70. package/gsd-core/references/research-documentation-lookup.md +29 -0
  71. package/gsd-core/references/research-philosophy.md +29 -0
  72. package/gsd-core/references/research-verification-protocol.md +27 -0
  73. package/gsd-core/workflows/execute-phase.md +19 -8
  74. package/gsd-core/workflows/help/modes/full.md +4 -3
  75. package/gsd-core/workflows/ingest-docs.md +3 -2
  76. package/gsd-core/workflows/plan-phase.md +14 -10
  77. package/gsd-core/workflows/plan-review-convergence.md +3 -3
  78. package/gsd-core/workflows/review.md +24 -7
  79. package/gsd-core/workflows/ship.md +5 -8
  80. package/gsd-core/workflows/spec-phase.md +2 -1
  81. package/gsd-core/workflows/update.md +34 -6
  82. package/hooks/dist/gsd-config-reload.js +133 -0
  83. package/hooks/dist/gsd-context-monitor.js +1 -1
  84. package/hooks/dist/gsd-cursor-post-tool.js +75 -0
  85. package/hooks/dist/gsd-cursor-session-start.js +52 -0
  86. package/hooks/dist/gsd-workflow-guard.js +1 -0
  87. package/hooks/dist/gsd-worktree-path-guard.js +1 -1
  88. package/hooks/dist/managed-hooks-registry.cjs +3 -0
  89. package/hooks/gsd-config-reload.js +133 -0
  90. package/hooks/gsd-context-monitor.js +1 -1
  91. package/hooks/gsd-cursor-post-tool.js +75 -0
  92. package/hooks/gsd-cursor-session-start.js +52 -0
  93. package/hooks/gsd-workflow-guard.js +1 -0
  94. package/hooks/gsd-worktree-path-guard.js +1 -1
  95. package/hooks/hooks.json +69 -0
  96. package/hooks/managed-hooks-registry.cjs +3 -0
  97. package/package.json +8 -1
  98. package/scripts/affected-tests-lib.cjs +3 -2
  99. package/scripts/build-hooks.js +7 -0
  100. package/scripts/changeset/cli.cjs +226 -28
  101. package/scripts/changeset/lint.cjs +5 -4
  102. package/scripts/changeset/new.cjs +4 -4
  103. package/scripts/check-alias-drift.cjs +77 -71
  104. package/scripts/check-env.cjs +185 -179
  105. package/scripts/check-npm-integrity.cjs +115 -109
  106. package/scripts/ci-guard-runner.cjs +11 -5
  107. package/scripts/ci-prepare-test-scope.cjs +27 -22
  108. package/scripts/ci-rebase-check.cjs +46 -45
  109. package/scripts/ci-test-scope.cjs +126 -22
  110. package/scripts/diff-touches-shipped-paths.cjs +52 -44
  111. package/scripts/gen-inventory-manifest.cjs +38 -32
  112. package/scripts/gen-research-agents.cjs +276 -0
  113. package/scripts/issue-dedupe.cjs +278 -0
  114. package/scripts/lib/cli-exit.cjs +56 -0
  115. package/scripts/lint-command-contract.cjs +28 -22
  116. package/scripts/lint-descriptions.cjs +32 -28
  117. package/scripts/lint-docs-required.cjs +4 -4
  118. package/scripts/lint-legacy-dir-name.cjs +56 -52
  119. package/scripts/lint-pr-check-project-dir.cjs +3 -1
  120. package/scripts/lint-shell-command-projection-drift.cjs +27 -22
  121. package/scripts/lint-skill-deps.cjs +31 -26
  122. package/scripts/lint-test-file-count.allowlist.json +2 -0
  123. package/scripts/lint-test-file-count.cjs +5 -4
  124. package/scripts/mutation-matrix.cjs +6 -3
  125. package/scripts/prompt-injection-scan.sh +1 -1
  126. package/scripts/release-notes/discord-release-summary.cjs +373 -0
  127. package/scripts/release-notes/format-github-release-notes.cjs +8 -3
  128. package/scripts/release-tarball-smoke.cjs +6 -4
  129. package/scripts/research-profiles.cjs +149 -0
  130. package/scripts/run-affected-tests.cjs +2 -1
  131. package/scripts/run-cross-platform-tests.cjs +11 -7
  132. package/scripts/run-tests.cjs +8 -7
  133. package/scripts/strip-prose-atrefs.cjs +1 -1
  134. package/scripts/sync-manifest-versions.cjs +119 -0
  135. package/scripts/sync-runtime-launcher.cjs +0 -3
  136. package/scripts/verify-npm-publish.cjs +14 -26
@@ -0,0 +1,276 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * gen-research-agents.cjs — profile-driven drift guard for the 7 researcher agents.
6
+ *
7
+ * Usage:
8
+ * node scripts/gen-research-agents.cjs # same as --check
9
+ * node scripts/gen-research-agents.cjs --check # assert every agent matches its profile
10
+ * node scripts/gen-research-agents.cjs --write # regenerate frontmatter from profiles
11
+ *
12
+ * --check assertions per agent:
13
+ * (a) frontmatter name/description/color/tools exactly match the profile
14
+ * (b) every requiredInclude string is present in the body
15
+ * (c) every requiredSeamCall string is present in the body
16
+ * (d) every outputContract marker string is present in the body
17
+ *
18
+ * --write regenerates ONLY the opening `---\n...\n---` frontmatter block from the
19
+ * profile, leaving the body byte-identical. After --write, --check must pass and
20
+ * `git diff` must be empty (profiles were derived from current state).
21
+ */
22
+
23
+ const fs = require('node:fs');
24
+ const path = require('node:path');
25
+
26
+ const { PROFILES } = require('./research-profiles.cjs');
27
+ const { ExitError, runMain } = require('./lib/cli-exit.cjs');
28
+
29
+ const ROOT = path.resolve(__dirname, '..');
30
+ const AGENTS_DIR = path.join(ROOT, 'agents');
31
+
32
+ // ─── Frontmatter serialization ────────────────────────────────────────────────
33
+
34
+ /**
35
+ * Build the frontmatter block for a profile.
36
+ *
37
+ * The agent files have two patterns for commented hooks:
38
+ * - Agents with Write in tools (file-writers): include the commented hooks block
39
+ * - The advisor-researcher (Read-only tools, no Write): no commented hooks
40
+ *
41
+ * We read the CURRENT commented-hooks block from the agent file and preserve it
42
+ * byte-for-byte; only name/description/tools/color are regenerated.
43
+ */
44
+ function buildFrontmatter(profile, existingFrontmatter) {
45
+ // Extract the commented hooks section from the existing frontmatter, if any.
46
+ // The hooks block starts at `# hooks:` and runs to (but not including) the
47
+ // closing `---`. In the committed files there is NO blank line between
48
+ // `color:` and `# hooks:`, so we append it directly after the color line's `\n`.
49
+ const hooksMatch = existingFrontmatter.match(/(# hooks:[\s\S]*?)(?=\n---)/);
50
+ // hooksSuffix: if present, the block followed by a newline so `---` is on its own line;
51
+ // if absent, empty string (the closing `---` follows directly after color's `\n`).
52
+ const hooksSuffix = hooksMatch ? hooksMatch[1] + '\n' : '';
53
+
54
+ return (
55
+ '---\n' +
56
+ 'name: ' + profile.name + '\n' +
57
+ 'description: ' + profile.description + '\n' +
58
+ 'tools: ' + profile.tools + '\n' +
59
+ 'color: ' + profile.color + '\n' +
60
+ hooksSuffix +
61
+ '---'
62
+ );
63
+ }
64
+
65
+ // ─── Parse agent file ─────────────────────────────────────────────────────────
66
+
67
+ /**
68
+ * Parse a .md file and return { frontmatterRaw, body, frontmatterFields }.
69
+ *
70
+ * frontmatterRaw: the raw text between the first and second `---` delimiters (exclusive)
71
+ * body: everything after the closing `---\n`
72
+ * frontmatterFields: { name, description, color, tools }
73
+ */
74
+ function parseAgentFile(filePath) {
75
+ const raw = fs.readFileSync(filePath, 'utf8');
76
+
77
+ // The frontmatter is between the first `---` line and the next `---` line.
78
+ const lines = raw.split('\n');
79
+ let start = -1;
80
+ let end = -1;
81
+ for (let i = 0; i < lines.length; i++) {
82
+ if (lines[i].trim() === '---') {
83
+ if (start === -1) {
84
+ start = i;
85
+ } else {
86
+ end = i;
87
+ break;
88
+ }
89
+ }
90
+ }
91
+
92
+ if (start === -1 || end === -1) {
93
+ throw new Error('No valid frontmatter delimiters found in ' + filePath);
94
+ }
95
+
96
+ const frontmatterLines = lines.slice(start + 1, end);
97
+ const frontmatterRaw = frontmatterLines.join('\n');
98
+ // body includes the closing `---` line and everything after
99
+ const fullFrontmatter = lines.slice(start, end + 1).join('\n');
100
+ const body = lines.slice(end + 1).join('\n');
101
+
102
+ const fields = {};
103
+ // Parse simple key: value pairs (not nested YAML, no multi-line values here)
104
+ for (const line of frontmatterLines) {
105
+ // Skip comment lines
106
+ if (line.trimStart().startsWith('#')) continue;
107
+ const m = line.match(/^(\w+):\s*(.*)/);
108
+ if (m) {
109
+ fields[m[1]] = m[2].trim();
110
+ }
111
+ }
112
+
113
+ return { raw, frontmatterRaw, fullFrontmatter, body, fields };
114
+ }
115
+
116
+ // ─── Check ────────────────────────────────────────────────────────────────────
117
+
118
+ /**
119
+ * Check one profile against its agent file.
120
+ * Returns an array of failure strings (empty = pass).
121
+ */
122
+ function checkAgent(profile) {
123
+ // Validate required array fields — return a clear failure rather than throwing TypeError.
124
+ for (const field of ['requiredIncludes', 'requiredSeamCalls', 'outputContract']) {
125
+ if (!Array.isArray(profile[field])) {
126
+ return ['profile ' + profile.name + ': missing required array field ' + field];
127
+ }
128
+ }
129
+
130
+ const agentPath = path.join(AGENTS_DIR, profile.name + '.md');
131
+ const failures = [];
132
+
133
+ if (!fs.existsSync(agentPath)) {
134
+ return ['agent file not found: ' + agentPath];
135
+ }
136
+
137
+ const { fields } = parseAgentFile(agentPath);
138
+ const fullContent = fs.readFileSync(agentPath, 'utf8');
139
+
140
+ // (a) frontmatter fields
141
+ if (fields.name !== profile.name) {
142
+ failures.push(
143
+ 'name mismatch: got "' + fields.name + '", want "' + profile.name + '"',
144
+ );
145
+ }
146
+ if (fields.description !== profile.description) {
147
+ failures.push(
148
+ 'description mismatch:\n got: "' + fields.description + '"\n want: "' + profile.description + '"',
149
+ );
150
+ }
151
+ if (fields.color !== profile.color) {
152
+ failures.push(
153
+ 'color mismatch: got "' + fields.color + '", want "' + profile.color + '"',
154
+ );
155
+ }
156
+ if (fields.tools !== profile.tools) {
157
+ failures.push(
158
+ 'tools mismatch:\n got: "' + fields.tools + '"\n want: "' + profile.tools + '"',
159
+ );
160
+ }
161
+
162
+ // (b) requiredIncludes
163
+ for (const include of profile.requiredIncludes) {
164
+ if (!fullContent.includes(include)) {
165
+ failures.push('missing required include: ' + include);
166
+ }
167
+ }
168
+
169
+ // (c) requiredSeamCalls
170
+ for (const seam of profile.requiredSeamCalls) {
171
+ if (!fullContent.includes(seam)) {
172
+ failures.push('missing required seam call: ' + seam);
173
+ }
174
+ }
175
+
176
+ // (d) outputContract
177
+ for (const marker of profile.outputContract) {
178
+ if (!fullContent.includes(marker)) {
179
+ failures.push('missing output contract marker: ' + marker);
180
+ }
181
+ }
182
+
183
+ return failures;
184
+ }
185
+
186
+ /**
187
+ * Run --check for all profiles. Prints pass/fail per agent.
188
+ * Returns true if all pass, false otherwise.
189
+ */
190
+ function runCheck() {
191
+ let allPassed = true;
192
+
193
+ for (const profile of PROFILES) {
194
+ const failures = checkAgent(profile);
195
+ if (failures.length === 0) {
196
+ process.stdout.write(' PASS ' + profile.name + '\n');
197
+ } else {
198
+ process.stdout.write(' FAIL ' + profile.name + '\n');
199
+ for (const f of failures) {
200
+ process.stdout.write(' ' + f.replace(/\n/g, '\n ') + '\n');
201
+ }
202
+ allPassed = false;
203
+ }
204
+ }
205
+
206
+ return allPassed;
207
+ }
208
+
209
+ // ─── Write ────────────────────────────────────────────────────────────────────
210
+
211
+ /**
212
+ * Regenerate the frontmatter block of one agent file from its profile.
213
+ * The body (everything after the closing ---) is preserved byte-for-byte.
214
+ */
215
+ function writeAgent(profile) {
216
+ const agentPath = path.join(AGENTS_DIR, profile.name + '.md');
217
+ const { fullFrontmatter, body } = parseAgentFile(agentPath);
218
+
219
+ const newFrontmatter = buildFrontmatter(profile, fullFrontmatter);
220
+ const newContent = newFrontmatter + '\n' + body;
221
+
222
+ fs.writeFileSync(agentPath, newContent, 'utf8');
223
+ }
224
+
225
+ function runWrite() {
226
+ for (const profile of PROFILES) {
227
+ const agentPath = path.join(AGENTS_DIR, profile.name + '.md');
228
+ if (!fs.existsSync(agentPath)) {
229
+ throw new ExitError(1, 'ERROR: agent file not found: ' + agentPath);
230
+ }
231
+ writeAgent(profile);
232
+ process.stdout.write(' wrote ' + profile.name + '.md\n');
233
+ }
234
+ process.stdout.write('\nRun --check to verify:\n');
235
+ process.stdout.write(' node scripts/gen-research-agents.cjs --check\n');
236
+ }
237
+
238
+ // ─── Exports (for tests) ──────────────────────────────────────────────────────
239
+
240
+ module.exports = { PROFILES, checkAgent, runCheck, parseAgentFile };
241
+
242
+ // ─── CLI entry point ──────────────────────────────────────────────────────────
243
+
244
+ function main() {
245
+ const flag = process.argv[2] || '--check';
246
+
247
+ if (flag === '--write') {
248
+ process.stdout.write('Writing frontmatter from profiles...\n');
249
+ runWrite();
250
+ process.stdout.write('\nVerifying...\n');
251
+ const ok = runCheck();
252
+ if (!ok) {
253
+ process.stderr.write('\nERROR: --check failed after --write. Fix serialization.\n');
254
+ throw new ExitError(1);
255
+ }
256
+ process.stdout.write('\nAll agents match their profiles.\n');
257
+ } else if (flag === '--check') {
258
+ process.stdout.write('Checking research agent profiles...\n');
259
+ const ok = runCheck();
260
+ if (!ok) {
261
+ process.stderr.write('\nSome agents do not match their profiles.\n');
262
+ process.stdout.write(
263
+ '\nTo regenerate frontmatter from profiles:\n' +
264
+ ' node scripts/gen-research-agents.cjs --write\n',
265
+ );
266
+ throw new ExitError(1);
267
+ }
268
+ process.stdout.write('\nAll 7 agents match their profiles.\n');
269
+ } else {
270
+ throw new ExitError(1, 'Unknown flag: ' + flag + '\nUsage: node scripts/gen-research-agents.cjs [--check|--write]');
271
+ }
272
+ }
273
+
274
+ if (require.main === module) {
275
+ runMain(main);
276
+ }
@@ -0,0 +1,278 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // ---------------------------------------------------------------------------
5
+ // Constants
6
+ // ---------------------------------------------------------------------------
7
+
8
+ const POSSIBLE_DUPLICATE_LABEL = 'possible-duplicate';
9
+ const HUMAN_REVIEW_LABEL = 'needs-maintainer-review';
10
+ const CHALLENGE_MARKER = '<!-- gsd-dedupe-challenge -->';
11
+ const DEFAULT_WINDOW_HOURS = 24;
12
+ const DEFAULT_THRESHOLD = 0.6;
13
+ const DEFAULT_MAX_CANDIDATES = 5;
14
+ const MIN_TOKEN_LENGTH = 3;
15
+
16
+ const EXEMPT_LABELS = [
17
+ 'priority: critical',
18
+ 'pinned',
19
+ 'confirmed-bug',
20
+ 'confirmed',
21
+ 'fix-pending',
22
+ 'needs-maintainer-review',
23
+ ];
24
+
25
+ const STOPWORDS = new Set([
26
+ 'the', 'a', 'an', 'and', 'or', 'but', 'if', 'then', 'is', 'are', 'was',
27
+ 'be', 'to', 'of', 'in', 'on', 'for', 'with', 'as', 'at', 'by', 'from',
28
+ 'this', 'that', 'it', 'its', 'not', 'no', 'when', 'what', 'why', 'how',
29
+ 'does', 'do', 'doing', 'did', 'can', 'will', 'would', 'should',
30
+ 'i', 'we', 'you', 'your', 'my', 'me',
31
+ 'issue', 'bug', 'error', 'problem', 'feature', 'request',
32
+ 'help', 'support', 'please', 'question',
33
+ 'after', 'before', 'into', 'only', 'then', 'than', 'them', 'they',
34
+ 'use', 'used', 'using',
35
+ ]);
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // tokenize(title) -> string[]
39
+ //
40
+ // Lowercase the title, replace any non-[a-z0-9] run with a space, split on
41
+ // whitespace, drop tokens shorter than MIN_TOKEN_LENGTH, drop STOPWORDS, and
42
+ // dedupe while preserving stable first-occurrence order.
43
+ //
44
+ // Non-string, null, or empty input returns []. Must not throw on any input.
45
+ // ---------------------------------------------------------------------------
46
+
47
+ function tokenize(title) {
48
+ if (typeof title !== 'string' || !title) return [];
49
+
50
+ const normalized = title.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
51
+ if (!normalized) return [];
52
+
53
+ const seen = new Set();
54
+ const result = [];
55
+
56
+ for (const token of normalized.split(' ')) {
57
+ if (!token || token.length < MIN_TOKEN_LENGTH) continue;
58
+ if (STOPWORDS.has(token)) continue;
59
+ if (seen.has(token)) continue;
60
+ seen.add(token);
61
+ result.push(token);
62
+ }
63
+
64
+ return result;
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // diceSimilarity(aTokens, bTokens) -> number 0..1
69
+ //
70
+ // Sørensen–Dice over the token sets: 2 * |A ∩ B| / (|A| + |B|).
71
+ // Both inputs are treated as sets (duplicates ignored). Empty either side -> 0.
72
+ // Identical sets -> 1.
73
+ // ---------------------------------------------------------------------------
74
+
75
+ function diceSimilarity(aTokens, bTokens) {
76
+ const setA = new Set(aTokens);
77
+ const setB = new Set(bTokens);
78
+
79
+ if (setA.size === 0 || setB.size === 0) return 0;
80
+
81
+ let intersection = 0;
82
+ for (const token of setA) {
83
+ if (setB.has(token)) intersection += 1;
84
+ }
85
+
86
+ return (2 * intersection) / (setA.size + setB.size);
87
+ }
88
+
89
+ // ---------------------------------------------------------------------------
90
+ // scoreCandidates(newTitle, candidates, opts) -> [{number, title, score}]
91
+ //
92
+ // opts: { threshold=DEFAULT_THRESHOLD, limit=DEFAULT_MAX_CANDIDATES, excludeNumber }
93
+ //
94
+ // Tokenizes newTitle once. If no tokens -> []. Filters out null/garbage
95
+ // candidates, those missing a number, and the excluded number. Scores each
96
+ // using diceSimilarity. Keeps score >= threshold. Sorts DESC by score,
97
+ // tie-break ASC by number. Caps to limit.
98
+ // ---------------------------------------------------------------------------
99
+
100
+ function scoreCandidates(newTitle, candidates, opts) {
101
+ const threshold = (opts && opts.threshold != null) ? opts.threshold : DEFAULT_THRESHOLD;
102
+ const limit = (opts && opts.limit != null) ? opts.limit : DEFAULT_MAX_CANDIDATES;
103
+ const excludeNumber = opts && opts.excludeNumber;
104
+
105
+ const newTokens = tokenize(newTitle);
106
+ if (newTokens.length === 0) return [];
107
+
108
+ const scored = [];
109
+
110
+ const safeCandidates = Array.isArray(candidates) ? candidates : [];
111
+ for (const candidate of safeCandidates) {
112
+ if (!candidate || typeof candidate !== 'object') continue;
113
+ if (!(typeof candidate.number === 'number' && Number.isFinite(candidate.number))) continue;
114
+ if (candidate.number === excludeNumber) continue;
115
+
116
+ const score = diceSimilarity(newTokens, tokenize(candidate.title));
117
+ if (score < threshold) continue;
118
+
119
+ scored.push({ number: candidate.number, title: candidate.title, score });
120
+ }
121
+
122
+ scored.sort((a, b) => {
123
+ if (Math.abs(a.score - b.score) > 1e-9) return b.score - a.score;
124
+ return a.number - b.number;
125
+ });
126
+
127
+ return scored.slice(0, limit);
128
+ }
129
+
130
+ // ---------------------------------------------------------------------------
131
+ // renderChallengeComment(candidates, opts) -> string
132
+ //
133
+ // opts: { windowHours=DEFAULT_WINDOW_HOURS }
134
+ //
135
+ // Deterministic. Must start with CHALLENGE_MARKER on its own line. Must list
136
+ // each candidate as a line with #<number>, title, and percentage similarity.
137
+ // Must mention windowHours and the 👎 veto.
138
+ // ---------------------------------------------------------------------------
139
+
140
+ function renderChallengeComment(candidates, opts) {
141
+ const windowHours = (opts && opts.windowHours != null) ? opts.windowHours : DEFAULT_WINDOW_HOURS;
142
+
143
+ const lines = [CHALLENGE_MARKER, ''];
144
+
145
+ lines.push('**Possible duplicate detected.** This issue may already be reported:');
146
+ lines.push('');
147
+
148
+ for (const candidate of candidates) {
149
+ const pct = Math.round(candidate.score * 100);
150
+ lines.push(`- #${candidate.number} — ${candidate.title} (similarity ${pct}%)`);
151
+ }
152
+
153
+ lines.push('');
154
+ lines.push(
155
+ `If this is **not** a duplicate, react with 👎 on this comment to veto and keep the issue open. ` +
156
+ `If no response is received within ${windowHours} hours, this issue may be closed as a duplicate.`,
157
+ );
158
+
159
+ return lines.join('\n');
160
+ }
161
+
162
+ // ---------------------------------------------------------------------------
163
+ // isChallengeComment(body) -> boolean
164
+ //
165
+ // True iff body is a string containing CHALLENGE_MARKER.
166
+ // ---------------------------------------------------------------------------
167
+
168
+ function isChallengeComment(body) {
169
+ if (typeof body !== 'string') return false;
170
+ return body.includes(CHALLENGE_MARKER);
171
+ }
172
+
173
+ // ---------------------------------------------------------------------------
174
+ // hasExemptLabel(labels) -> boolean
175
+ //
176
+ // labels may be an array of strings or array of {name}. True if any name is
177
+ // in EXEMPT_LABELS.
178
+ // ---------------------------------------------------------------------------
179
+
180
+ function hasExemptLabel(labels) {
181
+ if (!Array.isArray(labels)) return false;
182
+ const exemptSet = new Set(EXEMPT_LABELS);
183
+ for (const label of labels) {
184
+ const name = typeof label === 'string' ? label : (label && label.name);
185
+ if (name && exemptSet.has(name)) return true;
186
+ }
187
+ return false;
188
+ }
189
+
190
+ // ---------------------------------------------------------------------------
191
+ // toMs(value) -> number
192
+ //
193
+ // Coerce a Date, ISO string, or ms-number to milliseconds since epoch.
194
+ // ---------------------------------------------------------------------------
195
+
196
+ function toMs(value) {
197
+ if (value instanceof Date) return value.getTime();
198
+ if (typeof value === 'string') return new Date(value).getTime();
199
+ return Number(value);
200
+ }
201
+
202
+ // ---------------------------------------------------------------------------
203
+ // shouldClose(input) -> {close: boolean, reason: string}
204
+ //
205
+ // input: { now, labels, challengeComment, laterUserComments, windowHours=DEFAULT_WINDOW_HOURS }
206
+ //
207
+ // Decision order (returns first match):
208
+ // 1. hasExemptLabel(labels) -> {close:false, reason:'exempt-label'}
209
+ // 2. !challengeComment -> {close:false, reason:'no-challenge-comment'}
210
+ // 3. challengeComment.downvoted -> {close:false, reason:'vetoed'}
211
+ // 4. laterUserComments > 0 -> {close:false, reason:'reporter-responded'}
212
+ // 5. ageHours < windowHours -> {close:false, reason:'within-window'}
213
+ // 6. else -> {close:true, reason:'duplicate-no-response'}
214
+ // ---------------------------------------------------------------------------
215
+
216
+ function shouldClose(input) {
217
+ const {
218
+ now,
219
+ labels = [],
220
+ challengeComment,
221
+ laterUserComments = 0,
222
+ } = input;
223
+ const windowHours = (input.windowHours != null) ? input.windowHours : DEFAULT_WINDOW_HOURS;
224
+
225
+ if (hasExemptLabel(labels)) {
226
+ return { close: false, reason: 'exempt-label' };
227
+ }
228
+
229
+ if (!challengeComment) {
230
+ return { close: false, reason: 'no-challenge-comment' };
231
+ }
232
+
233
+ if (challengeComment.downvoted) {
234
+ return { close: false, reason: 'vetoed' };
235
+ }
236
+
237
+ if (laterUserComments > 0) {
238
+ return { close: false, reason: 'reporter-responded' };
239
+ }
240
+
241
+ const nowMs = toMs(now);
242
+ const createdMs = toMs(challengeComment.createdAt);
243
+
244
+ if (!Number.isFinite(nowMs) || !Number.isFinite(createdMs)) {
245
+ return { close: false, reason: 'invalid-timestamp' };
246
+ }
247
+
248
+ const ageHours = (nowMs - createdMs) / 3600000;
249
+
250
+ if (ageHours < windowHours) {
251
+ return { close: false, reason: 'within-window' };
252
+ }
253
+
254
+ return { close: true, reason: 'duplicate-no-response' };
255
+ }
256
+
257
+ // ---------------------------------------------------------------------------
258
+ // Exports
259
+ // ---------------------------------------------------------------------------
260
+
261
+ module.exports = {
262
+ POSSIBLE_DUPLICATE_LABEL,
263
+ HUMAN_REVIEW_LABEL,
264
+ CHALLENGE_MARKER,
265
+ DEFAULT_WINDOW_HOURS,
266
+ DEFAULT_THRESHOLD,
267
+ DEFAULT_MAX_CANDIDATES,
268
+ MIN_TOKEN_LENGTH,
269
+ EXEMPT_LABELS,
270
+ STOPWORDS,
271
+ tokenize,
272
+ diceSimilarity,
273
+ scoreCandidates,
274
+ renderChallengeComment,
275
+ isChallengeComment,
276
+ hasExemptLabel,
277
+ shouldClose,
278
+ };
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Error that carries a process exit code. CLI logic throws this instead of
5
+ * calling process.exit() (banned by n/no-process-exit); runMain() translates it
6
+ * into process.exitCode at the entrypoint.
7
+ *
8
+ * @param {number} code exit code (default 1)
9
+ * @param {string} [message] optional human message; when set and code != 0 it is
10
+ * written to stderr by runMain before the process exits.
11
+ */
12
+ class ExitError extends Error {
13
+ constructor(code = 1, message) {
14
+ super(message === undefined ? `process exit ${code}` : message);
15
+ this.name = 'ExitError';
16
+ this.code = code;
17
+ // Whether runMain should print this.message to stderr (only when a real
18
+ // message was provided, not the synthetic default).
19
+ this.hasUserMessage = message !== undefined;
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Run a CLI main function and translate its outcome into process.exitCode
25
+ * (never process.exit(), so n/no-process-exit stays satisfied). Supports sync or
26
+ * async main.
27
+ * - main returns a number -> process.exitCode = that number
28
+ * - main throws/rejects ExitError -> process.exitCode = err.code, and if
29
+ * err.hasUserMessage && err.code !== 0, err.message is written to stderr
30
+ * - main throws/rejects anything else -> the stack is written to stderr and
31
+ * process.exitCode = 1
32
+ * Letting the event loop drain (vs process.exit) means buffered stdout/stderr is
33
+ * flushed and process.on('exit') cleanup handlers still fire.
34
+ *
35
+ * @param {() => (number|void|Promise<number|void>)} main
36
+ */
37
+ function runMain(main) {
38
+ Promise.resolve()
39
+ .then(() => main())
40
+ .then((code) => {
41
+ if (typeof code === 'number') process.exitCode = code;
42
+ })
43
+ .catch((err) => {
44
+ if (err instanceof ExitError) {
45
+ if (err.hasUserMessage && err.code !== 0) {
46
+ process.stderr.write(`${err.message}\n`);
47
+ }
48
+ process.exitCode = err.code;
49
+ return;
50
+ }
51
+ process.stderr.write(`${err && err.stack ? err.stack : String(err)}\n`);
52
+ process.exitCode = 1;
53
+ });
54
+ }
55
+
56
+ module.exports = { ExitError, runMain };
@@ -28,6 +28,8 @@ const {
28
28
  executionContextRefs: extractExecutionContextRefs,
29
29
  } = require('./command-contract-helpers.cjs');
30
30
 
31
+ const { runMain } = require('./lib/cli-exit.cjs');
32
+
31
33
  // ─── check one file ───────────────────────────────────────────────────────────
32
34
 
33
35
  function check(filePath) {
@@ -79,30 +81,34 @@ function check(filePath) {
79
81
 
80
82
  // ─── run ─────────────────────────────────────────────────────────────────────
81
83
 
82
- const commandFiles = fs
83
- .readdirSync(COMMANDS_DIR)
84
- .filter(f => f.endsWith('.md'))
85
- .map(f => path.join(COMMANDS_DIR, f));
84
+ function main() {
85
+ const commandFiles = fs
86
+ .readdirSync(COMMANDS_DIR)
87
+ .filter(f => f.endsWith('.md'))
88
+ .map(f => path.join(COMMANDS_DIR, f));
86
89
 
87
- const results = commandFiles.map(check).filter(Boolean);
90
+ const results = commandFiles.map(check).filter(Boolean);
88
91
 
89
- if (results.length === 0) {
90
- console.log(
91
- `ok lint-command-contract: ${commandFiles.length} command files checked, 0 violations`,
92
- );
93
- process.exit(0);
94
- }
92
+ if (results.length === 0) {
93
+ console.log(
94
+ `ok lint-command-contract: ${commandFiles.length} command files checked, 0 violations`,
95
+ );
96
+ return 0;
97
+ }
95
98
 
96
- const total = results.reduce((n, r) => n + r.violations.length, 0);
97
- process.stderr.write(
98
- `\nERROR lint-command-contract: ${total} violation(s) across ${results.length} file(s)\n\n`,
99
- );
100
- for (const r of results) {
101
- process.stderr.write(` ${r.file}\n`);
102
- for (const v of r.violations) {
103
- process.stderr.write(` - ${v}\n`);
99
+ const total = results.reduce((n, r) => n + r.violations.length, 0);
100
+ process.stderr.write(
101
+ `\nERROR lint-command-contract: ${total} violation(s) across ${results.length} file(s)\n\n`,
102
+ );
103
+ for (const r of results) {
104
+ process.stderr.write(` ${r.file}\n`);
105
+ for (const v of r.violations) {
106
+ process.stderr.write(` - ${v}\n`);
107
+ }
108
+ process.stderr.write('\n');
104
109
  }
105
- process.stderr.write('\n');
110
+ process.stderr.write('See docs/adr/0002-command-contract-validation-module.md for the contract spec.\n\n');
111
+ return 1;
106
112
  }
107
- process.stderr.write('See docs/adr/0002-command-contract-validation-module.md for the contract spec.\n\n');
108
- process.exit(1);
113
+
114
+ runMain(main);