specgate-cli 0.0.0-stage → 0.1.7

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,33 @@
1
+ # language: en
2
+ # Gherkin example: the same requirements as SPEC.md, written as a feature file.
3
+ #
4
+ # `specgate` reads both. A scenario with an explicit tag (@AC-1) keeps the
5
+ # same id as the markdown criterion, so the two files describe ONE
6
+ # requirement, not two.
7
+
8
+ Feature: Invoice export
9
+
10
+ Background:
11
+ Given an account exists
12
+
13
+ @AC-1
14
+ Scenario: Export invoices as CSV
15
+ Given an invoice exists
16
+ When the user requests an export
17
+ Then a CSV file is produced
18
+
19
+ @AC-2
20
+ Scenario: Export respects the date range filter
21
+ Given invoices exist
22
+ When the user filters by date range
23
+ Then only invoices in range are exported
24
+
25
+ Scenario: Export is emailed to the account owner
26
+ Given an account exists
27
+ When the export completes
28
+ Then the file is emailed to the account owner
29
+
30
+ Scenario: Export fails loudly when storage is unavailable
31
+ Given the storage backend is unavailable
32
+ When the user requests an export
33
+ Then the failure is reported to the user
@@ -0,0 +1,26 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /**
5
+ * Minimal stand-in for the real export service. It only exists so the
6
+ * gherkin example has something to match evidence against.
7
+ */
8
+
9
+ export function exportInvoicesCsv(invoices) {
10
+ if (!invoices || invoices.length === 0) {
11
+ throw new Error('no invoices to export');
12
+ }
13
+ const header = 'id,amount,date';
14
+ const rows = invoices.map((i) => `${i.id},${i.amount},${i.date}`);
15
+ return [header, ...rows].join('\n');
16
+ }
17
+
18
+ export function filterByDateRange(invoices, from, to) {
19
+ return invoices.filter((i) => i.date >= from && i.date <= to);
20
+ }
21
+
22
+ export function writeExportFile(dir, csv) {
23
+ const target = path.join(dir, 'export.csv');
24
+ fs.writeFileSync(target, csv, 'utf8');
25
+ return target;
26
+ }
@@ -0,0 +1,21 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+
4
+ import { exportInvoicesCsv, filterByDateRange } from '../src/export.js';
5
+
6
+ const INVOICES = [
7
+ { id: 'i1', amount: 10, date: '2026-01-05' },
8
+ { id: 'i2', amount: 20, date: '2026-02-05' },
9
+ ];
10
+
11
+ test('exports invoices as CSV', () => {
12
+ const csv = exportInvoicesCsv(INVOICES);
13
+ assert.match(csv, /id,amount,date/);
14
+ assert.match(csv, /i1,10,2026-01-05/);
15
+ });
16
+
17
+ test('filters invoices by date range', () => {
18
+ const filtered = filterByDateRange(INVOICES, '2026-02-01', '2026-02-28');
19
+ assert.equal(filtered.length, 1);
20
+ assert.equal(filtered[0].id, 'i2');
21
+ });
@@ -0,0 +1,12 @@
1
+ # Example: Invoice Export — Specification
2
+
3
+ A tiny feature spec used to demonstrate `specgate`. Run `specgate` in this
4
+ directory to see requirement coverage reported against the code.
5
+
6
+ ## Acceptance Criteria
7
+
8
+ - [ ] AC-1: User can export invoices as CSV
9
+ - [ ] AC-2: Export respects the date range filter
10
+ - [ ] AC-3: Exported file is emailed to the account owner
11
+ - [ ] AC-4: Export fails loudly when the storage backend is unavailable
12
+ - [ ] AC-5: Admin can schedule a recurring monthly export
@@ -0,0 +1,20 @@
1
+ // Invoice CSV export.
2
+ //
3
+ // AC-1: User can export invoices as CSV
4
+ // AC-2: Export respects the date range filter
5
+
6
+ export function exportInvoicesCsv(invoices, { from, to } = {}) {
7
+ const rows = invoices.filter((inv) => inRange(inv, from, to));
8
+ const header = 'id,amount,currency,issued_at';
9
+ const body = rows
10
+ .map((inv) => `${inv.id},${inv.amount},${inv.currency},${inv.issuedAt}`)
11
+ .join('\n');
12
+ return `${header}\n${body}\n`;
13
+ }
14
+
15
+ function inRange(invoice, from, to) {
16
+ const at = new Date(invoice.issuedAt).getTime();
17
+ if (from && at < new Date(from).getTime()) return false;
18
+ if (to && at > new Date(to).getTime()) return false;
19
+ return true;
20
+ }
@@ -0,0 +1,18 @@
1
+ // Email delivery of exports.
2
+ //
3
+ // AC-3: Exported file is emailed to the account owner
4
+ // AC-4: Export fails loudly when the storage backend is unavailable
5
+
6
+ export async function emailExport(account, csv) {
7
+ const backend = await loadStorageBackend();
8
+ if (!backend) {
9
+ // Deliberately loud: a silent failure here ships empty invoices to
10
+ // customers, which is worse than a broken page.
11
+ throw new Error('storage backend unavailable: cannot deliver export');
12
+ }
13
+ return backend.deliver(account.email, 'invoice-export.csv', csv);
14
+ }
15
+
16
+ async function loadStorageBackend() {
17
+ return globalThis.__storageBackend ?? null;
18
+ }
@@ -0,0 +1,27 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+
4
+ import { exportInvoicesCsv } from '../src/export.js';
5
+
6
+ const invoices = [
7
+ { id: 'i1', amount: 100, currency: 'USD', issuedAt: '2026-01-15' },
8
+ { id: 'i2', amount: 250, currency: 'USD', issuedAt: '2026-02-20' },
9
+ { id: 'i3', amount: 75, currency: 'EUR', issuedAt: '2026-03-05' },
10
+ ];
11
+
12
+ // AC-1: User can export invoices as CSV
13
+ test('exports invoices as CSV with a header row', () => {
14
+ const csv = exportInvoicesCsv(invoices);
15
+ const lines = csv.trim().split('\n');
16
+ assert.equal(lines[0], 'id,amount,currency,issued_at');
17
+ assert.equal(lines.length, 4);
18
+ assert.ok(lines[1].startsWith('i1,100,USD'));
19
+ });
20
+
21
+ // AC-2: Export respects the date range filter
22
+ test('respects the date range filter', () => {
23
+ const csv = exportInvoicesCsv(invoices, { from: '2026-02-01', to: '2026-02-28' });
24
+ const lines = csv.trim().split('\n');
25
+ assert.equal(lines.length, 2);
26
+ assert.ok(lines[1].startsWith('i2,'));
27
+ });
@@ -0,0 +1,4 @@
1
+ [package]
2
+ name = "rust-counter"
3
+ version = "0.1.0"
4
+ edition = "2021"
@@ -0,0 +1,7 @@
1
+ # Rust counter
2
+
3
+ ## Acceptance Criteria
4
+
5
+ - [ ] AC-1: Increasing the counter increases the total
6
+ - [ ] AC-2: A new counter starts at zero
7
+ - [ ] AC-3: Persist counter history across application restarts
@@ -0,0 +1,19 @@
1
+ #[derive(Default)]
2
+ pub struct Counter(pub u32);
3
+
4
+ impl Counter {
5
+ pub fn increment(&mut self) {
6
+ self.0 += 1;
7
+ }
8
+ }
9
+
10
+ #[cfg(test)]
11
+ mod tests {
12
+ use super::Counter;
13
+
14
+ #[test]
15
+ fn new_counter_is_zero() {
16
+ // AC-2
17
+ assert_eq!(Counter::default().0, 0);
18
+ }
19
+ }
@@ -0,0 +1,9 @@
1
+ use rust_counter::Counter;
2
+
3
+ #[test]
4
+ fn increments_counter() {
5
+ // AC-1
6
+ let mut counter = Counter::default();
7
+ counter.increment();
8
+ assert_eq!(counter.0, 1);
9
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "specgate-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.7",
4
+ "description": "Requirement coverage for your codebase. Like test coverage, but for acceptance criteria. Deterministic, no LLM at runtime.",
5
+ "type": "module",
6
+ "bin": {
7
+ "specgate": "bin/specgate.js"
8
+ },
9
+ "main": "src/index.js",
10
+ "exports": {
11
+ ".": "./src/index.js"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "src",
16
+ "assets",
17
+ "examples",
18
+ "README.md",
19
+ "action.yml",
20
+ "LICENSE"
21
+ ],
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "scripts": {
26
+ "test": "node --test test/*.test.js",
27
+ "lint": "node --check bin/specgate.js"
28
+ },
29
+ "keywords": [
30
+ "spec",
31
+ "requirements",
32
+ "acceptance-criteria",
33
+ "coverage",
34
+ "quality-gate",
35
+ "ci",
36
+ "testing",
37
+ "traceability",
38
+ "ai-generated-code",
39
+ "code-review"
40
+ ],
41
+ "license": "MIT",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/aazh2026/specgate.git"
45
+ },
46
+ "homepage": "https://github.com/aazh2026/specgate",
47
+ "bugs": {
48
+ "url": "https://github.com/aazh2026/specgate/issues"
49
+ }
50
+ }
package/src/aliases.js ADDED
@@ -0,0 +1,151 @@
1
+ /**
2
+ * TypeScript path aliases.
3
+ *
4
+ * A project with `paths` in its tsconfig imports modules by a short alias:
5
+ *
6
+ * import { writeAuditLog } from '@/lib/audit-writer';
7
+ *
8
+ * The real file is `src/lib/audit-writer.ts`. A criterion that talks about
9
+ * "the audit writer" should be able to find that file, and a test that
10
+ * imports the aliased module should carry the module's name as searchable
11
+ * text.
12
+ *
13
+ * This module resolves an import specifier to the file it actually points
14
+ * at, so the matcher can index the alias name as evidence.
15
+ */
16
+
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+
20
+ const RESOLVE_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.svelte'];
21
+
22
+ /**
23
+ * Strip comments and trailing commas from a tsconfig.
24
+ *
25
+ * A tsconfig is JSONC, not JSON: `//` and `/* *\/` comments are legal, and
26
+ * trailing commas are legal. `JSON.parse` rejects both.
27
+ */
28
+ export function parseJsonc(text) {
29
+ const withoutComments = String(text)
30
+ .replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, comment) => (comment ? '' : m))
31
+ .replace(/,(\s*[}\]])/g, '$1');
32
+ return JSON.parse(withoutComments);
33
+ }
34
+
35
+ /**
36
+ * Read `compilerOptions.paths` (and `baseUrl`) from a tsconfig.
37
+ *
38
+ * @param {string} root the repository root
39
+ * @returns {{baseUrl: string|null, paths: Record<string,string[]>}|null}
40
+ */
41
+ export function readPathAliases(root) {
42
+ const file = path.join(root, 'tsconfig.json');
43
+ if (!fs.existsSync(file)) return null;
44
+
45
+ let json;
46
+ try {
47
+ json = parseJsonc(fs.readFileSync(file, 'utf8'));
48
+ } catch {
49
+ return null;
50
+ }
51
+
52
+ const opts = json.compilerOptions || {};
53
+ if (!opts.paths || typeof opts.paths !== 'object') return null;
54
+
55
+ const baseUrl = opts.baseUrl
56
+ ? path.resolve(root, opts.baseUrl)
57
+ : root;
58
+
59
+ const paths = {};
60
+ for (const [pattern, targets] of Object.entries(opts.paths)) {
61
+ if (!Array.isArray(targets)) continue;
62
+ paths[pattern] = targets.filter((t) => typeof t === 'string');
63
+ }
64
+ if (!Object.keys(paths).length) return null;
65
+
66
+ return { baseUrl, paths };
67
+ }
68
+
69
+ /**
70
+ * Does an import specifier match a tsconfig path pattern?
71
+ *
72
+ * `@/*` matches `@/lib/audit-writer` with remainder `lib/audit-writer`.
73
+ * A pattern without `*` only matches itself.
74
+ */
75
+ function matchPattern(pattern, specifier) {
76
+ const star = pattern.indexOf('*');
77
+ if (star === -1) {
78
+ return pattern === specifier ? '' : null;
79
+ }
80
+ const prefix = pattern.slice(0, star);
81
+ const suffix = pattern.slice(star + 1);
82
+ if (!specifier.startsWith(prefix)) return null;
83
+ if (!specifier.endsWith(suffix)) return null;
84
+ return specifier.slice(prefix.length, specifier.length - suffix.length);
85
+ }
86
+
87
+ /** Candidate absolute paths for one alias target, in preference order. */
88
+ function candidates(baseUrl, target, remainder) {
89
+ const raw = target.includes('*') ? target.replace('*', remainder) : target;
90
+ const abs = path.resolve(baseUrl, raw);
91
+ const out = [];
92
+
93
+ // Exact file.
94
+ out.push(abs);
95
+ // With a known extension.
96
+ if (!path.extname(abs)) {
97
+ for (const ext of RESOLVE_EXTENSIONS) out.push(abs + ext);
98
+ }
99
+ // Directory index.
100
+ for (const ext of RESOLVE_EXTENSIONS) out.push(path.join(abs, `index${ext}`));
101
+
102
+ return out;
103
+ }
104
+
105
+ /**
106
+ * Resolve an import specifier to the real file it points at.
107
+ *
108
+ * @param {string} specifier e.g. `@/lib/audit-writer`
109
+ * @param {{baseUrl: string|null, paths: Record<string,string[]>}|null} aliases
110
+ * @returns {string|null} absolute path of the target file, or null
111
+ */
112
+ export function resolveAlias(specifier, aliases) {
113
+ if (!aliases || !specifier) return null;
114
+ // A relative or absolute import is not an alias.
115
+ if (specifier.startsWith('.') || specifier.startsWith('/')) return null;
116
+
117
+ for (const [pattern, targets] of Object.entries(aliases.paths)) {
118
+ const remainder = matchPattern(pattern, specifier);
119
+ if (remainder === null) continue;
120
+ for (const target of targets) {
121
+ for (const cand of candidates(aliases.baseUrl, target, remainder)) {
122
+ try {
123
+ if (fs.existsSync(cand) && fs.statSync(cand).isFile()) return cand;
124
+ } catch {
125
+ /* unreadable: try the next candidate */
126
+ }
127
+ }
128
+ }
129
+ }
130
+ return null;
131
+ }
132
+
133
+ const IMPORT_RE = /(?:^|[\s;])(?:import|export)\s+(?:[^'"]*?\sfrom\s+)?['"]([^'"]+)['"]|(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
134
+
135
+ /**
136
+ * Every import specifier in a file's source.
137
+ *
138
+ * @param {string} content
139
+ * @returns {string[]}
140
+ */
141
+ export function extractImportSpecifiers(content) {
142
+ const out = [];
143
+ const source = String(content);
144
+ IMPORT_RE.lastIndex = 0;
145
+ let m;
146
+ while ((m = IMPORT_RE.exec(source)) !== null) {
147
+ const spec = m[1] || m[2];
148
+ if (spec) out.push(spec);
149
+ }
150
+ return out;
151
+ }
package/src/index.js ADDED
@@ -0,0 +1,175 @@
1
+ /**
2
+ * specgate public API.
3
+ *
4
+ * runSpecgate({ root, specFiles }) -> report
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+
11
+ import { parseSpec } from './spec/parse.js';
12
+ import { parseFeature } from './spec/gherkin.js';
13
+ import { collectCodeFiles, findSpecFiles } from './walk.js';
14
+ import { readPathAliases } from './aliases.js';
15
+ import { indexFiles, matchCriterion } from './matcher.js';
16
+ import { computeScore } from './report.js';
17
+
18
+ // Read the version from package.json so it can never drift from the published
19
+ // package.
20
+ function readVersion() {
21
+ try {
22
+ const here = path.dirname(fileURLToPath(import.meta.url));
23
+ const pkg = JSON.parse(fs.readFileSync(path.join(here, '..', 'package.json'), 'utf8'));
24
+ return pkg.version || '0.0.0';
25
+ } catch {
26
+ return '0.0.0';
27
+ }
28
+ }
29
+
30
+ export const VERSION = readVersion();
31
+
32
+ /**
33
+ * The scope a criterion id belongs to.
34
+ *
35
+ * Ids are unique inside a project, not inside a file: a `SPEC.md` at the
36
+ * project root and a `features/export.feature` describe the same project, so
37
+ * `@AC-1` in both is one requirement. But two different projects — two
38
+ * example directories in this repo, say — each have their own `AC-1`.
39
+ *
40
+ * The scope is therefore the spec file's directory, with a trailing
41
+ * `features/` (or `spec/`) stripped so a feature file and a root spec land in
42
+ * the same scope.
43
+ */
44
+ function specScope(file) {
45
+ const dir = String(file).split('/').slice(0, -1).join('/');
46
+ const parts = dir.split('/').filter(Boolean);
47
+ if (parts.length && (parts[parts.length - 1] === 'features' || parts[parts.length - 1] === 'spec')) {
48
+ parts.pop();
49
+ }
50
+ return parts.join('/') || '.';
51
+ }
52
+
53
+ /**
54
+ * @param {{root: string, specFiles?: string[], scope?: string}} options
55
+ * `scope` restricts which files count as evidence. Specs are still
56
+ * discovered across the whole repository: in a monorepo the spec usually
57
+ * lives in one package while the implementation is spread over several.
58
+ */
59
+ export function runSpecgate(options) {
60
+ const root = path.resolve(options.root || '.');
61
+ const specPaths = findSpecFiles(root, options.specFiles || []);
62
+
63
+ const criteria = [];
64
+ const specs = [];
65
+
66
+ for (const specPath of specPaths) {
67
+ const content = fs.readFileSync(specPath, 'utf8');
68
+ const rel = path.relative(root, specPath).split(path.sep).join('/');
69
+ // A `.feature` file is Gherkin, not markdown. Parsing it with the
70
+ // markdown parser would silently find nothing.
71
+ const parsed = /\.feature$/i.test(rel)
72
+ ? parseFeature(content, { file: rel })
73
+ : parseSpec(content, { file: rel });
74
+ const specIndex = specs.length;
75
+ specs.push({
76
+ file: rel,
77
+ criteria: parsed.criteria.length,
78
+ headings: parsed.headings.length,
79
+ });
80
+ for (const c of parsed.criteria) {
81
+ criteria.push({ ...c, _spec: specIndex });
82
+ }
83
+ }
84
+
85
+ // Deduplicate criteria that appear in several spec files.
86
+ //
87
+ // Rule 1 (global): the same id *and* the same text → one requirement
88
+ // described twice, e.g. the same bullet copied into two files.
89
+ //
90
+ // Rule 2 (scoped): the same explicit id with different wording → still one
91
+ // requirement, but only inside one spec scope. This is what lets a SPEC.md
92
+ // and a feature file in the same project describe the same criterion
93
+ // without double-counting it, while two unrelated projects (for example two
94
+ // example directories in this repo) keep their own AC-1.
95
+ //
96
+ // Whatever gets dropped or merged is subtracted from the per-spec counts,
97
+ // so `sum(specs[].criteria) === summary.total` always holds.
98
+ const byScopeAndId = new Map();
99
+ const seen = new Set();
100
+ const unique = [];
101
+
102
+ for (const c of criteria) {
103
+ const scope = specScope(c.file);
104
+ // The slug is part of the key, so the scope has to be part of it too:
105
+ // two different projects can have an `AC-1` whose text slugifies to the
106
+ // same string, and those are two requirements.
107
+ const key = `${scope}::${c.normalisedId}::${c.slug}`;
108
+ if (seen.has(key)) {
109
+ specs[c._spec].criteria -= 1;
110
+ continue;
111
+ }
112
+
113
+ const scopedId = `${scope}::${c.normalisedId}`;
114
+ const existing = byScopeAndId.get(scopedId);
115
+
116
+ if (existing) {
117
+ if (existing.source === 'explicit' && c.source === 'explicit') {
118
+ // Same requirement, two wordings: merge the searchable phrasings so
119
+ // evidence can match either one.
120
+ const texts = new Set([
121
+ ...(existing.searchTexts || [existing.text]),
122
+ ...(c.searchTexts || [c.text]),
123
+ ]);
124
+ existing.searchTexts = [...texts];
125
+ existing.alsoIn = [...new Set([...(existing.alsoIn || []), c.file])];
126
+ specs[c._spec].criteria -= 1;
127
+ continue;
128
+ }
129
+ // An explicit id beats a minted one: drop the minted duplicate.
130
+ if (existing.source !== 'explicit' && c.source === 'explicit') {
131
+ specs[existing._spec].criteria -= 1;
132
+ const at = unique.indexOf(existing);
133
+ if (at !== -1) unique[at] = c;
134
+ byScopeAndId.set(scopedId, c);
135
+ seen.add(key);
136
+ continue;
137
+ }
138
+ specs[c._spec].criteria -= 1;
139
+ continue;
140
+ }
141
+
142
+ seen.add(key);
143
+ byScopeAndId.set(scopedId, c);
144
+ unique.push(c);
145
+ }
146
+
147
+ for (const c of unique) delete c._spec;
148
+
149
+ const aliases = readPathAliases(root);
150
+ const codeFiles = collectCodeFiles(root, { scope: options.scope, aliases });
151
+ const indexed = indexFiles(codeFiles);
152
+
153
+ const results = unique.map((criterion) => {
154
+ const match = matchCriterion(criterion, indexed);
155
+ return { ...criterion, ...match };
156
+ });
157
+
158
+ return {
159
+ version: VERSION,
160
+ root,
161
+ specs,
162
+ criteria: results,
163
+ summary: computeScore(results),
164
+ stats: {
165
+ filesScanned: codeFiles.length,
166
+ testFiles: codeFiles.filter((f) => f.isTest).length,
167
+ },
168
+ };
169
+ }
170
+
171
+ export { parseSpec } from './spec/parse.js';
172
+ export { parseFeature } from './spec/gherkin.js';
173
+ export { computeScore, renderText, renderJson, renderSarif } from './report.js';
174
+ export { extractTags, keyTerms, matchCriterion } from './matcher.js';
175
+ export { STATUS_LABEL, STATUS_WEIGHT } from './status.js';