specgate-cli 0.0.0-stage → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Parse a Gherkin/Cucumber `.feature` file into acceptance criteria.
3
+ *
4
+ * A feature file is already a spec, so each scenario is a requirement:
5
+ *
6
+ * @AC-1
7
+ * Scenario: Export invoices as CSV
8
+ * Given an invoice exists
9
+ * When the user requests an export
10
+ * Then a CSV file is produced
11
+ *
12
+ * Two ways to give a scenario an id:
13
+ * 1. an explicit tag (`@AC-1`) — the criterion then matches a tagged test
14
+ * exactly like a markdown criterion does, so one requirement can be
15
+ * described in both a SPEC.md and a feature file and still be one id;
16
+ * 2. otherwise we mint `SC-<n>` in document order.
17
+ *
18
+ * The scenario *name* is the human-readable requirement text. The steps are
19
+ * kept separately as `searchText`, because a step definition usually says
20
+ * something like `Given('the user requests an export')` and that wording is
21
+ * better evidence than the scenario title alone.
22
+ */
23
+
24
+ import { normaliseId, tokenize } from './parse.js';
25
+
26
+ const FEATURE_RE = /^\s*Feature\s*:\s*(.*)$/i;
27
+ const RULE_RE = /^\s*Rule\s*:\s*(.*)$/i;
28
+ const BACKGROUND_RE = /^\s*Background\s*:\s*(.*)$/i;
29
+ const SCENARIO_RE = /^\s*Scenario(?: Outline| Template)?\s*:\s*(.*)$/i;
30
+ const EXAMPLES_RE = /^\s*Examples\s*:/i;
31
+ const STEP_RE = /^\s*(Given|When|Then|And|But|\*)\s+(.*)$/i;
32
+ const TAG_RE = /^\s*@([A-Za-z0-9_.\-]+)/;
33
+ const TABLE_ROW_RE = /^\s*\|/;
34
+
35
+ /** Tags that look like a criterion id (`AC-1`, `S3`, `REQ_2`). */
36
+ const ID_TAG_RE = /^[A-Za-z]{1,6}[-_ ]?\d+(?:[._]\d+)*$/;
37
+
38
+ /**
39
+ * @param {string} content raw feature file text
40
+ * @param {{file?: string}} [opts]
41
+ * @returns {{criteria: Array<object>, headings: Array<object>}}
42
+ */
43
+ export function parseFeature(content, opts = {}) {
44
+ const file = opts.file || '<feature>';
45
+ const lines = String(content).split(/\r?\n/);
46
+
47
+ const criteria = [];
48
+ const headings = [];
49
+
50
+ let featureName = 'Feature';
51
+ let section = 'Feature';
52
+ let pendingTags = [];
53
+ let scenario = null;
54
+ let scenarioCounter = 0;
55
+ let inExamples = false;
56
+
57
+ const closeScenario = () => {
58
+ if (!scenario) return;
59
+ criteria.push(scenario);
60
+ scenario = null;
61
+ };
62
+
63
+ for (let i = 0; i < lines.length; i++) {
64
+ const line = lines[i];
65
+
66
+ // Skip blank lines, comments and table rows.
67
+ if (!line.trim()) continue;
68
+ if (/^\s*#/.test(line)) continue;
69
+ if (TABLE_ROW_RE.test(line)) continue;
70
+
71
+ const tag = TAG_RE.exec(line);
72
+ if (tag) {
73
+ pendingTags.push(tag[1]);
74
+ continue;
75
+ }
76
+
77
+ const feature = FEATURE_RE.exec(line);
78
+ if (feature) {
79
+ closeScenario();
80
+ featureName = feature[1].trim() || 'Feature';
81
+ section = featureName;
82
+ headings.push({ title: featureName, level: 1, line: i + 1 });
83
+ pendingTags = [];
84
+ continue;
85
+ }
86
+
87
+ const rule = RULE_RE.exec(line);
88
+ if (rule) {
89
+ closeScenario();
90
+ section = rule[1].trim() || 'Rule';
91
+ headings.push({ title: section, level: 2, line: i + 1 });
92
+ pendingTags = [];
93
+ continue;
94
+ }
95
+
96
+ if (BACKGROUND_RE.test(line)) {
97
+ closeScenario();
98
+ pendingTags = [];
99
+ continue;
100
+ }
101
+
102
+ if (EXAMPLES_RE.test(line)) {
103
+ // The Examples table is data for the outline, not a separate scenario.
104
+ inExamples = true;
105
+ continue;
106
+ }
107
+
108
+ const sc = SCENARIO_RE.exec(line);
109
+ if (sc) {
110
+ closeScenario();
111
+ inExamples = false;
112
+ scenarioCounter += 1;
113
+ const name = sc[1].trim();
114
+ const isOutline = /outline|template/i.test(sc[0]);
115
+ const idTag = pendingTags.find((t) => ID_TAG_RE.test(t));
116
+ const id = idTag || `SC-${scenarioCounter}`;
117
+ pendingTags = [];
118
+ scenario = {
119
+ id,
120
+ normalisedId: normaliseId(id),
121
+ text: name,
122
+ slug: slugify(name),
123
+ section,
124
+ line: i + 1,
125
+ file,
126
+ checked: false,
127
+ source: idTag ? 'explicit' : 'inferred',
128
+ steps: [],
129
+ isOutline,
130
+ };
131
+ headings.push({ title: name, level: 3, line: i + 1 });
132
+ continue;
133
+ }
134
+
135
+ const step = STEP_RE.exec(line);
136
+ if (step && scenario) {
137
+ if (inExamples) continue;
138
+ scenario.steps.push(step[2].trim());
139
+ continue;
140
+ }
141
+
142
+ // Any other content ends the current step block but not the scenario.
143
+ if (scenario && !inExamples) {
144
+ // A free-text line inside a scenario is still part of the requirement.
145
+ scenario.steps.push(line.trim());
146
+ }
147
+ }
148
+
149
+ closeScenario();
150
+
151
+ // The searchable text of a criterion includes its steps: step definitions
152
+ // in the code are usually phrased like the step, not like the title.
153
+ for (const c of criteria) {
154
+ c.searchTexts = [c.text, ...c.steps].filter((t) => t && t.trim());
155
+ }
156
+
157
+ return { criteria, headings };
158
+ }
159
+
160
+ function slugify(text, max = 48) {
161
+ const tokens = tokenize(text).slice(0, 6);
162
+ const base = tokens.join('-') || 'scenario';
163
+ return base.slice(0, max);
164
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Parse a spec document into a list of acceptance criteria.
3
+ *
4
+ * Supported shapes (all optional, mixed freely):
5
+ * ## Acceptance Criteria
6
+ * - [ ] AC-1: User can reset their password
7
+ * - [ ] [AC-2] Export runs as CSV
8
+ * - [ ] AC3 S3. Writes an audit log entry
9
+ * - [ ] Given a locked account, when the user retries 3 times, then it is suspended
10
+ *
11
+ * Every criterion gets a stable id. If the author wrote an explicit id we keep
12
+ * it verbatim (case-insensitively normalised for matching); otherwise we mint
13
+ * `AC-<n>` in document order so the tool still works on unstructured specs.
14
+ */
15
+
16
+ const ID_RE = /^\[?([A-Za-z]{1,5}[-_ ]?\d+(?:[._]\d+)*)\]?\s*(?:[::\-–—]\s*)?(.*)$/;
17
+
18
+ // Headings that turn a plain bullet list into acceptance criteria.
19
+ const ACCEPTANCE_HEADING_RE =
20
+ /^(acceptance\s+criteria|acceptance|ac|requirements?|user\s+stories?|criteria|验收标准|需求|用户故事)\b/i;
21
+
22
+ const STOPWORDS = new Set([
23
+ 'a', 'an', 'the', 'and', 'or', 'of', 'to', 'in', 'on', 'for', 'with', 'is',
24
+ 'are', 'be', 'it', 'that', 'this', 'as', 'at', 'by', 'from', 'can', 'should',
25
+ 'must', 'will', 'shall', 'user', 'users', 'when', 'then', 'given', 'system',
26
+ 'i', 'if', 'so', 'not', 'no', 'they', 'their', 'has', 'have', 'had', 'but',
27
+ ]);
28
+
29
+ /** Normalise an id for comparison: `AC-1`, `ac 1`, `AC_1` all become `ac-1`. */
30
+ export function normaliseId(raw) {
31
+ return String(raw)
32
+ .toLowerCase()
33
+ .trim()
34
+ .replace(/[\s_]+/g, '-')
35
+ .replace(/-+/g, '-');
36
+ }
37
+
38
+ /**
39
+ * Split text into meaningful lowercase tokens.
40
+ *
41
+ * Identifier boundaries matter: code says `resetPassword`, `export_csv`,
42
+ * `HTTPResponse`. A naive split on non-alphanumerics would produce one
43
+ * meaningless token and break every match against real source files.
44
+ */
45
+ export function tokenize(text) {
46
+ const expanded = String(text)
47
+ // camelCase / PascalCase boundaries
48
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
49
+ // ACRONYM followed by a word: HTTPServer -> HTTPServer
50
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
51
+ // snake_case and kebab-case
52
+ .replace(/[_\-.]+/g, ' ');
53
+
54
+ return expanded
55
+ .toLowerCase()
56
+ .split(/[^a-z0-9一-鿿]+/i)
57
+ .map((t) => t.trim())
58
+ .filter((t) => t.length > 1 && !STOPWORDS.has(t));
59
+ }
60
+
61
+ function slugify(text, max = 48) {
62
+ const tokens = tokenize(text).slice(0, 6);
63
+ const base = tokens.join('-') || 'criterion';
64
+ return base.slice(0, max);
65
+ }
66
+
67
+ function headingLevel(line) {
68
+ const m = /^(#{1,6})\s+(.*)$/.exec(line);
69
+ return m ? { level: m[1].length, title: m[2].trim() } : null;
70
+ }
71
+
72
+ /**
73
+ * @param {string} content raw spec text
74
+ * @param {{file?: string}} [opts]
75
+ * @returns {{criteria: Array<object>, headings: Array<object>}}
76
+ */
77
+ export function parseSpec(content, opts = {}) {
78
+ const file = opts.file || '<spec>';
79
+ const lines = String(content).split(/\r?\n/);
80
+
81
+ const criteria = [];
82
+ const headings = [];
83
+ let inFence = false;
84
+ let currentHeading = null;
85
+ let headingLevelNow = 0;
86
+ let acceptanceMode = false;
87
+ let autoCounter = 0;
88
+
89
+ for (let i = 0; i < lines.length; i++) {
90
+ const line = lines[i];
91
+
92
+ if (/^\s*```/.test(line)) {
93
+ inFence = !inFence;
94
+ continue;
95
+ }
96
+ if (inFence) continue;
97
+
98
+ const h = headingLevel(line);
99
+ if (h) {
100
+ currentHeading = h.title;
101
+ headingLevelNow = h.level;
102
+ headings.push({ title: h.title, level: h.level, line: i + 1 });
103
+ // Acceptance mode ends when a new heading at the same or shallower level appears.
104
+ if (headingLevelNow <= headingLevelNow || true) {
105
+ acceptanceMode = ACCEPTANCE_HEADING_RE.test(h.title);
106
+ }
107
+ continue;
108
+ }
109
+
110
+ // A bullet, optionally with a checkbox.
111
+ const bullet = /^\s*(?:[-*+]|\d+[.)])\s+(\[[ xX]\]\s*)?(.*)$/.exec(line);
112
+ if (!bullet) continue;
113
+
114
+ const body = (bullet[2] || '').trim();
115
+ if (!body) continue;
116
+
117
+ // Only treat bullets as criteria when we are inside an acceptance-criteria
118
+ // section, OR when the bullet carries an explicit id like `AC-1:`.
119
+ const explicit = ID_RE.exec(body);
120
+ const hasExplicitId = Boolean(explicit && explicit[1] && /\d/.test(explicit[1]));
121
+ if (!acceptanceMode && !hasExplicitId) continue;
122
+
123
+ autoCounter += 1;
124
+ let id;
125
+ let text;
126
+ if (hasExplicitId) {
127
+ id = explicit[1];
128
+ text = (explicit[2] || '').trim() || body;
129
+ } else {
130
+ id = `AC-${autoCounter}`;
131
+ text = body;
132
+ }
133
+
134
+ criteria.push({
135
+ id,
136
+ normalisedId: normaliseId(id),
137
+ text,
138
+ slug: slugify(text),
139
+ section: currentHeading || 'Acceptance Criteria',
140
+ line: i + 1,
141
+ file,
142
+ checked: Boolean(bullet[1]),
143
+ source: hasExplicitId ? 'explicit' : 'inferred',
144
+ });
145
+ }
146
+
147
+ return { criteria, headings };
148
+ }
package/src/status.js ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Criterion statuses and their weights.
3
+ *
4
+ * covered explicit evidence: a test (or source) references the criterion id
5
+ * inferred a test name or body matches the criterion's distinctive words
6
+ * untested only implementation code matched — nothing pins the behaviour
7
+ * uncovered no evidence found at all
8
+ */
9
+
10
+ export const STATUS_LABEL = {
11
+ covered: 'covered',
12
+ inferred: 'inferred',
13
+ untested: 'untested',
14
+ uncovered: 'uncovered',
15
+ };
16
+
17
+ export const STATUS_WEIGHT = {
18
+ covered: 1.0,
19
+ inferred: 0.75,
20
+ untested: 0.4,
21
+ uncovered: 0.0,
22
+ };
23
+
24
+ export const STATUS_ORDER = ['covered', 'inferred', 'untested', 'uncovered'];
package/src/walk.js ADDED
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Repository walking + spec discovery.
3
+ */
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+
8
+ import { extractImportSpecifiers, resolveAlias } from './aliases.js';
9
+
10
+ const IGNORE_DIRS = new Set([
11
+ '.git', 'node_modules', '.venv', 'venv', 'dist', 'build', 'out', 'coverage',
12
+ '__pycache__', '.mypy_cache', '.pytest_cache', '.next', '.nuxt', 'target',
13
+ 'vendor', '.idea', '.vscode', '.tox', 'site-packages', '.cache',
14
+ ]);
15
+
16
+ const CODE_EXT = new Set([
17
+ '.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.py', '.rb', '.go', '.rs',
18
+ '.java', '.kt', '.kts', '.c', '.h', '.cc', '.cpp', '.hpp', '.cs', '.php',
19
+ '.swift', '.scala', '.sh', '.bash', '.sql',
20
+ ]);
21
+
22
+ const TEST_HINT = /(^|[.\-/])(test|tests|spec|specs|__tests__)([.\-/]|$)|[._-](test|spec)\.[a-z]+$|\.test\.|\.spec\./i;
23
+
24
+ export function isCodeFile(filePath) {
25
+ return CODE_EXT.has(path.extname(filePath).toLowerCase());
26
+ }
27
+
28
+ /** True when `file` lives inside `dir` (or is `dir` itself). */
29
+ function isInside(dir, file) {
30
+ const rel = path.relative(dir, file);
31
+ if (!rel) return true;
32
+ if (rel.startsWith('..')) return false;
33
+ return !path.isAbsolute(rel);
34
+ }
35
+
36
+ export function isTestFile(filePath, content = '') {
37
+ // Rust's inline tests live in modules compiled only in the test configuration.
38
+ if (/\.rs$/i.test(filePath) && /^[ \t]*#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]\s*(?:pub\s+)?mod\s+\w+\s*\{/m.test(content)) return true;
39
+ const base = path.basename(filePath);
40
+ if (/(^test_.*\.py$)|(_test\.py$)|(test\.py$)|(^conftest\.py$)/i.test(base)) return true;
41
+ if (/\.(test|spec)\.[a-z]+$/i.test(base)) return true;
42
+ if (/(^tests?[\/\\])|([\/\\]tests?[\/\\])|([\/\\]__tests__[\/\\])/i.test(filePath)) return true;
43
+ return TEST_HINT.test(filePath);
44
+ }
45
+
46
+ /** Recursively list files under a directory, skipping noisy folders. */
47
+ export function walk(root, opts = {}) {
48
+ const out = [];
49
+ const maxFiles = opts.maxFiles || 20000;
50
+ const stack = [root];
51
+
52
+ while (stack.length) {
53
+ const dir = stack.pop();
54
+ let entries;
55
+ try {
56
+ entries = fs.readdirSync(dir, { withFileTypes: true });
57
+ } catch {
58
+ continue;
59
+ }
60
+ for (const entry of entries) {
61
+ if (out.length >= maxFiles) return out;
62
+ const full = path.join(dir, entry.name);
63
+ if (entry.isDirectory()) {
64
+ if (IGNORE_DIRS.has(entry.name)) continue;
65
+ if (entry.name.startsWith('.') && entry.name !== '.github') continue;
66
+ stack.push(full);
67
+ } else if (entry.isFile()) {
68
+ out.push(full);
69
+ }
70
+ }
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /**
76
+ * Find candidate spec documents in the repository.
77
+ * Preference order: explicit config, then conventional locations.
78
+ */
79
+ export function findSpecFiles(root, explicit = []) {
80
+ const found = [];
81
+ const seen = new Set();
82
+
83
+ const push = (p) => {
84
+ const abs = path.resolve(p);
85
+ // Compare lower-cased so a case-insensitive filesystem (macOS, Windows)
86
+ // cannot report the same file twice under two spellings.
87
+ const key = abs.toLowerCase();
88
+ if (!seen.has(key) && fs.existsSync(abs) && fs.statSync(abs).isFile()) {
89
+ seen.add(key);
90
+ found.push(abs);
91
+ }
92
+ };
93
+
94
+ for (const p of explicit) push(path.resolve(root, p));
95
+
96
+ const conventions = [
97
+ 'SPEC.md', 'spec.md', 'SPECIFICATION.md', 'specification.md',
98
+ 'REQUIREMENTS.md', 'requirements.md', 'PRD.md', 'prd.md',
99
+ 'docs/SPEC.md', 'docs/spec.md', 'docs/requirements.md',
100
+ 'docs/acceptance-criteria.md', 'spec/SPEC.md', '.specgate/spec.md',
101
+ ];
102
+ for (const c of conventions) push(path.join(root, c));
103
+
104
+ // Any markdown that contains an acceptance-criteria section, plus any
105
+ // Gherkin feature file (a feature file is a spec by construction).
106
+ for (const file of walk(root, { maxFiles: 4000 })) {
107
+ const isMarkdown = /\.md$/i.test(file);
108
+ const isFeature = /\.feature$/i.test(file);
109
+ if (!isMarkdown && !isFeature) continue;
110
+ const rel = path.relative(root, file);
111
+ if (/(^|\/)(node_modules|vendor|dist|build)\//.test(rel)) continue;
112
+ try {
113
+ const content = fs.readFileSync(file, 'utf8');
114
+ if (isFeature) {
115
+ push(file);
116
+ continue;
117
+ }
118
+ if (/^\s{0,3}#{1,6}\s.*(acceptance\s+criteria|验收标准|acceptance)/im.test(content)) {
119
+ push(file);
120
+ }
121
+ } catch {
122
+ /* unreadable file: ignore */
123
+ }
124
+ }
125
+
126
+ return found;
127
+ }
128
+
129
+ /**
130
+ * Read source files that can hold evidence.
131
+ *
132
+ * @param {string} root the repository root
133
+ * @param {{maxFiles?: number, scope?: string, aliases?: object|null}} [opts]
134
+ * `scope` restricts which files count as evidence, relative to `root`.
135
+ * The specs are still discovered across the whole repository — in a
136
+ * monorepo the spec usually lives in one package while the implementation
137
+ * is spread across several.
138
+ * `aliases` is the tsconfig `paths` map; aliased imports are resolved so
139
+ * the real module's name can be searched.
140
+ */
141
+ export function collectCodeFiles(root, opts = {}) {
142
+ const files = [];
143
+ const scope = opts.scope ? path.resolve(root, opts.scope) : null;
144
+ const aliases = opts.aliases || null;
145
+
146
+ for (const file of walk(root, { maxFiles: opts.maxFiles || 20000 })) {
147
+ if (!isCodeFile(file)) continue;
148
+ const rel = path.relative(root, file);
149
+ if (/(^|\/)(node_modules|vendor|dist|build|out)\//.test(rel)) continue;
150
+ // When a scope is given, only files inside it can be evidence. A file
151
+ // outside the scope must not satisfy a criterion, even if its wording
152
+ // matches.
153
+ if (scope && !isInside(scope, file)) continue;
154
+ try {
155
+ const stat = fs.statSync(file);
156
+ if (stat.size > 512 * 1024) continue;
157
+ const content = fs.readFileSync(file, 'utf8');
158
+
159
+ // Resolve aliased imports to the real files, so a criterion that talks
160
+ // about the module behind `@/lib/audit-writer` can find it.
161
+ const aliasSpecifiers = [];
162
+ const aliasTargets = [];
163
+ if (aliases) {
164
+ for (const specifier of extractImportSpecifiers(content)) {
165
+ const resolved = resolveAlias(specifier, aliases);
166
+ if (!resolved) continue;
167
+ aliasSpecifiers.push(specifier);
168
+ const targetRel = path.relative(root, resolved).split(path.sep).join('/');
169
+ if (!targetRel.startsWith('..')) aliasTargets.push(targetRel);
170
+ }
171
+ }
172
+
173
+ files.push({
174
+ path: rel.split(path.sep).join('/'),
175
+ absPath: file,
176
+ isTest: isTestFile(rel, content),
177
+ content,
178
+ // The alias specifiers this file imports through a tsconfig path.
179
+ aliasSpecifiers,
180
+ // The real files those aliases point at.
181
+ aliasTargets,
182
+ // The file's own path is searchable only when the project actually
183
+ // uses path aliases. Without a tsconfig, nothing changes.
184
+ searchPath: aliases ? rel.split(path.sep).join('/') : '',
185
+ moduleName: null,
186
+ });
187
+ } catch {
188
+ /* skip unreadable */
189
+ }
190
+ }
191
+ for (const f of files) {
192
+ // When the project uses path aliases, a file's own name is part of what
193
+ // the code calls it: `src/lib/audit-writer.ts` is "the audit writer" to
194
+ // anyone writing an acceptance criterion, even if the file body never
195
+ // says so. Without a tsconfig this stays null and nothing changes.
196
+ if (aliases) {
197
+ f.moduleName = path.basename(f.path).replace(/\.[^.]+$/, '');
198
+ }
199
+ }
200
+
201
+ return files;
202
+ }