@specdest/devkit 0.3.4 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -3
- package/package.json +11 -4
- package/src/canonical-project-operations.js +210 -22
- package/src/canonical-project.js +25 -9
- package/src/canonical-source.js +37 -5
- package/src/cli.js +5 -2
- package/src/fuzz.js +291 -0
- package/src/git-catalog.js +74 -2
- package/src/index.js +4 -2
- package/src/project-targeting.js +48 -0
- package/src/remote-installer.js +2 -1
- package/src/rule-profile.js +61 -0
- package/src/sync-core.js +34 -6
package/README.md
CHANGED
|
@@ -9,19 +9,42 @@ The npm package contains only the CLI/core runtime. Canonical rules stay in the
|
|
|
9
9
|
```bash
|
|
10
10
|
npx @specdest/devkit status
|
|
11
11
|
npx @specdest/devkit sync
|
|
12
|
-
npx @specdest/devkit check
|
|
12
|
+
npx @specdest/devkit check [--refresh]
|
|
13
|
+
npx @specdest/devkit rules
|
|
13
14
|
npx @specdest/devkit doctor
|
|
15
|
+
npx @specdest/devkit fuzz
|
|
14
16
|
```
|
|
15
17
|
|
|
16
18
|
- `status` reads the cached canonical catalog and reports applicable/current/missing/outdated rules. Use `--refresh` to refresh the catalog from GitHub and `--json` for machine-readable output.
|
|
17
19
|
- `sync` refreshes the canonical catalog, downloads only missing rule-cache entries, installs missing applicable rules, and updates outdated ones.
|
|
18
|
-
- `check`
|
|
20
|
+
- `check` executes each distinct canonical checker implementation once from the local Devkit cache, projects that result onto every rule backed by that checker, and updates `.specdest/state.json`. Use `--refresh` to refresh the canonical catalog/checker cache first without reconciling project files.
|
|
21
|
+
- `rules` loads AI-facing guidance without dumping the whole catalog. Use `--id <rule>`, `--category <category>`, `--failed`, or `--json`; with no selector it returns only rules marked `ai.load = "always"`.
|
|
19
22
|
- `doctor` reports project-stack/cache setup problems.
|
|
23
|
+
- `fuzz` dynamically exercises Zod boundary contracts with `fast-check` plus Specdest semantic amplifiers for nullish, blank-string, numeric/boolean, and array edge cases. It is separate from static `check` and from Stryker mutation testing.
|
|
20
24
|
|
|
21
|
-
The CLI recognizes the supported Expo/Vite + Convex/Supabase stacks from the target repository's `package.json`. `.specdest/installed.json` and `.specdest/state.json` remain the committed project status used by the Base rules matrix.
|
|
25
|
+
The CLI recognizes the supported Expo/Vite + Convex/Supabase stacks from the target repository's `package.json`. Optional `.specdest/rules.json` adds project capabilities plus explicit rule includes/exclusions; every exclusion requires a reason. `.specdest/installed.json` and `.specdest/state.json` remain the committed project status used by the Base rules matrix.
|
|
22
26
|
|
|
23
27
|
See [`docs/operations.md`](docs/operations.md) for cache, dashboard, CI, and release behavior.
|
|
24
28
|
|
|
29
|
+
## Contract fuzzing
|
|
30
|
+
|
|
31
|
+
`npx @specdest/devkit fuzz` runs against the current repository. By default it discovers the boundary filenames already used by the canonical architecture rules: `*.input.schema.ts`, `*.output.schema.ts`, `*.form.schema.ts`, and `*.callbackInput.schema.ts` under `src/` and `supabase/functions/`. It loads the project's own Zod schemas; Devkit does not require or bundle a second runtime Zod instance.
|
|
32
|
+
|
|
33
|
+
The v1 adapter supports Zod objects, strings, numbers, booleans, arrays, enums, optional, nullable/nullish wrappers, and practical min/max boundaries. It amplifies values such as `null`, `undefined`, omitted properties, empty/whitespace strings, `0`, `false`, `NaN`, empty arrays, nullish array items, duplicates, reordering, and item removal. Accepted empty/whitespace strings are reported as semantic failures because they are commonly indistinguishable from absent user input at Specdest boundaries. Failures include the fast-check seed/path when applicable.
|
|
34
|
+
|
|
35
|
+
If default discovery is not appropriate, add `.specdest/fuzz.json`:
|
|
36
|
+
|
|
37
|
+
```json
|
|
38
|
+
{
|
|
39
|
+
"schemaVersion": 1,
|
|
40
|
+
"targets": [
|
|
41
|
+
{ "module": "src/application/user/update.input.schema.ts", "exports": ["userUpdateInputSchema"] }
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Current module loading supports Node 24 TypeScript, extensionless relative imports, and the Specdest `@/* -> src/*` alias convention. Unsupported schema constructs or unloadable modules are reported explicitly as `SKIP`; they are never silently interpreted.
|
|
47
|
+
|
|
25
48
|
## Canonical cache runtime
|
|
26
49
|
|
|
27
50
|
Canonical authoring lives under `modules/**`. The CLI refreshes a single-branch bare Git source and hydrates required modules from the same catalog revision into the local Devkit cache and materializes their `.agents/skills/**` target layout **inside the cache** so checker-relative imports keep working without copying canonical skills/checkers into project repositories. `catalog/**` is compatibility/test data, not a rule-authoring source.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@specdest/devkit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"specdest": "src/cli.js"
|
|
@@ -23,7 +23,8 @@
|
|
|
23
23
|
"scripts": {
|
|
24
24
|
"test": "node --test test/*.test.js",
|
|
25
25
|
"lint": "node scripts/validate-js.mjs",
|
|
26
|
-
"check": "pnpm run lint && pnpm run typecheck && pnpm run test",
|
|
26
|
+
"check": "pnpm run lint && pnpm run rules:validate && pnpm run rules:audit && pnpm run typecheck && pnpm run test",
|
|
27
|
+
"rules:validate": "node scripts/validate-rule-authoring.mjs",
|
|
27
28
|
"catalog:snapshot": "node scripts/export-catalog-snapshot.mjs",
|
|
28
29
|
"release:preflight": "node scripts/release-preflight.mjs",
|
|
29
30
|
"smoke:published": "node scripts/smoke-published-package.mjs",
|
|
@@ -31,10 +32,16 @@
|
|
|
31
32
|
"release:build": "node scripts/build-release-artifacts.mjs",
|
|
32
33
|
"smoke:artifact": "node scripts/smoke-package-artifact.mjs",
|
|
33
34
|
"runtime:build": "node scripts/build-remote-runtime.mjs",
|
|
34
|
-
"catalog:git": "node scripts/export-git-catalog.mjs"
|
|
35
|
+
"catalog:git": "node scripts/export-git-catalog.mjs",
|
|
36
|
+
"rules:audit": "node scripts/generate-rule-audit.mjs --check",
|
|
37
|
+
"rules:audit:write": "node scripts/generate-rule-audit.mjs"
|
|
35
38
|
},
|
|
36
39
|
"devDependencies": {
|
|
37
40
|
"@types/node": "^24.0.0",
|
|
38
|
-
"typescript": "^6.0.0"
|
|
41
|
+
"typescript": "^6.0.0",
|
|
42
|
+
"zod": "^4.6.4"
|
|
43
|
+
},
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"fast-check": "^4.10.0"
|
|
39
46
|
}
|
|
40
47
|
}
|
|
@@ -5,7 +5,9 @@ import { join, relative } from 'node:path';
|
|
|
5
5
|
import { createCanonicalSource, detectProjectStack } from './canonical-source.js';
|
|
6
6
|
import { applicableCatalogEntries, prepareCachedManifest } from './canonical-project.js';
|
|
7
7
|
import { installRule, syncRule } from './remote-installer.js';
|
|
8
|
-
import {
|
|
8
|
+
import { assertKnownRuleOverrides, readRuleProfile } from './rule-profile.js';
|
|
9
|
+
import { resolveProjectType } from './project-targeting.js';
|
|
10
|
+
import { readChecksState, readInstalledState, writeChecksState, writeInstalledState } from './sync-core.js';
|
|
9
11
|
|
|
10
12
|
function execute(command, args, cwd) {
|
|
11
13
|
return new Promise((resolve, reject) => {
|
|
@@ -47,7 +49,10 @@ async function cachedManifest(source, entry, canonicalCheckRoot, checkerRuntimeR
|
|
|
47
49
|
async function canonicalContext(projectRoot, source, options = {}) {
|
|
48
50
|
const catalog = await source.catalog({ refresh: options.refresh ?? false });
|
|
49
51
|
const stack = await detectProjectStack(projectRoot);
|
|
50
|
-
const
|
|
52
|
+
const profile = await readRuleProfile(projectRoot);
|
|
53
|
+
assertKnownRuleOverrides(catalog.entries ?? [], profile);
|
|
54
|
+
const projectType = resolveProjectType(stack, profile);
|
|
55
|
+
const applicable = applicableCatalogEntries(catalog.entries ?? [], stack, profile);
|
|
51
56
|
const canonicalCheck = (catalog.entries ?? []).find((entry) => entry.id === 'canonical-check');
|
|
52
57
|
const checkerRuntime = (catalog.entries ?? []).find((entry) => entry.id === 'checker-runtime');
|
|
53
58
|
let canonicalCheckRoot = null;
|
|
@@ -62,12 +67,12 @@ async function canonicalContext(projectRoot, source, options = {}) {
|
|
|
62
67
|
checkerRuntimeRoot = await source.module(checkerRuntime.id, checkerRuntime.version, { contentHash: checkerRuntime.contentHash });
|
|
63
68
|
}
|
|
64
69
|
}
|
|
65
|
-
return { catalog, stack, applicable, canonicalCheckRoot, checkerRuntimeRoot };
|
|
70
|
+
return { catalog, stack, projectType, profile, applicable, canonicalCheckRoot, checkerRuntimeRoot };
|
|
66
71
|
}
|
|
67
72
|
|
|
68
73
|
export async function canonicalStatus(projectRoot, source, options = {}) {
|
|
69
74
|
const current = await readInstalledState(projectRoot);
|
|
70
|
-
const { stack, applicable } = await canonicalContext(projectRoot, source, options);
|
|
75
|
+
const { stack, projectType, applicable } = await canonicalContext(projectRoot, source, options);
|
|
71
76
|
const installed = current.installed;
|
|
72
77
|
const rows = applicable.map((entry) => {
|
|
73
78
|
const found = installed[entry.id];
|
|
@@ -78,6 +83,7 @@ export async function canonicalStatus(projectRoot, source, options = {}) {
|
|
|
78
83
|
const installedNonApplicable = Object.keys(installed).filter((id) => !applicableIds.has(id)).sort();
|
|
79
84
|
return {
|
|
80
85
|
stack,
|
|
86
|
+
projectType,
|
|
81
87
|
totals: {
|
|
82
88
|
applicable: rows.length,
|
|
83
89
|
current: rows.filter((row) => row.state === 'current').length,
|
|
@@ -89,6 +95,44 @@ export async function canonicalStatus(projectRoot, source, options = {}) {
|
|
|
89
95
|
};
|
|
90
96
|
}
|
|
91
97
|
|
|
98
|
+
async function refreshInstalledRevision(projectRoot, id, revision) {
|
|
99
|
+
const state = await readInstalledState(projectRoot);
|
|
100
|
+
if (!state.installed[id]) throw new Error(`Installed rule missing during provenance refresh: ${id}`);
|
|
101
|
+
state.installed[id] = { ...state.installed[id], revision };
|
|
102
|
+
await writeInstalledState(projectRoot, state);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function cleanupCanonicalInstallState(projectRoot, catalogEntries) {
|
|
106
|
+
const installedState = await readInstalledState(projectRoot);
|
|
107
|
+
const catalogRules = new Set(
|
|
108
|
+
(catalogEntries ?? []).filter((entry) => entry.kind === 'rule').map((entry) => entry.id),
|
|
109
|
+
);
|
|
110
|
+
const requestedStacks = new Set(
|
|
111
|
+
installedState.requested.filter((id) => id.startsWith('stack-')),
|
|
112
|
+
);
|
|
113
|
+
const removed = [];
|
|
114
|
+
for (const id of Object.keys(installedState.installed)) {
|
|
115
|
+
if (catalogRules.has(id) || requestedStacks.has(id)) continue;
|
|
116
|
+
delete installedState.installed[id];
|
|
117
|
+
removed.push(id);
|
|
118
|
+
}
|
|
119
|
+
const nextRequested = installedState.requested.filter(
|
|
120
|
+
(id) => id.startsWith('stack-') && Boolean(installedState.installed[id]),
|
|
121
|
+
);
|
|
122
|
+
const requestedChanged = JSON.stringify(nextRequested) !== JSON.stringify(installedState.requested);
|
|
123
|
+
installedState.requested = nextRequested;
|
|
124
|
+
if (!removed.length && !requestedChanged) return [];
|
|
125
|
+
await writeInstalledState(projectRoot, installedState);
|
|
126
|
+
|
|
127
|
+
const runtimeState = await readChecksState(projectRoot);
|
|
128
|
+
for (const id of removed) {
|
|
129
|
+
delete runtimeState.results[id];
|
|
130
|
+
if (runtimeState.ownership) delete runtimeState.ownership[id];
|
|
131
|
+
}
|
|
132
|
+
await writeChecksState(projectRoot, runtimeState);
|
|
133
|
+
return removed.sort();
|
|
134
|
+
}
|
|
135
|
+
|
|
92
136
|
async function cleanupCanonicalSkillTree(projectRoot, allowedFiles) {
|
|
93
137
|
const root = join(projectRoot, '.agents', 'skills');
|
|
94
138
|
async function walk(directory) {
|
|
@@ -111,7 +155,7 @@ async function cleanupCanonicalSkillTree(projectRoot, allowedFiles) {
|
|
|
111
155
|
|
|
112
156
|
export async function canonicalSync(projectRoot, source) {
|
|
113
157
|
const current = await readInstalledState(projectRoot);
|
|
114
|
-
const { stack, applicable, canonicalCheckRoot, checkerRuntimeRoot } = await canonicalContext(projectRoot, source, { refresh: true, withCheckers: true });
|
|
158
|
+
const { catalog, stack, projectType, applicable, canonicalCheckRoot, checkerRuntimeRoot } = await canonicalContext(projectRoot, source, { refresh: true, withCheckers: true });
|
|
115
159
|
const changed = [];
|
|
116
160
|
const allowedSkillFiles = new Set();
|
|
117
161
|
for (const entry of applicable) {
|
|
@@ -124,25 +168,57 @@ export async function canonicalSync(projectRoot, source) {
|
|
|
124
168
|
if (!installed) {
|
|
125
169
|
await installRule({ projectRoot, payloadRoot: source.cachedModulePath(entry.id, entry.version), manifest: prepared.manifest });
|
|
126
170
|
changed.push({ id: entry.id, action: 'installed', version: entry.version });
|
|
127
|
-
} else
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
171
|
+
} else {
|
|
172
|
+
const requiresContentSync =
|
|
173
|
+
installed.version !== entry.version ||
|
|
174
|
+
installed.contentHash !== entry.contentHash ||
|
|
175
|
+
(prepared.checkerPath && installed.check?.command?.[0] !== 'specdest-cache') ||
|
|
176
|
+
await missingProjectScaffold(projectRoot, prepared.manifest.copies);
|
|
177
|
+
if (requiresContentSync) {
|
|
178
|
+
await syncRule({ projectRoot, payloadRoot: source.cachedModulePath(entry.id, entry.version), manifest: prepared.manifest });
|
|
179
|
+
changed.push({ id: entry.id, action: 'updated', version: entry.version });
|
|
180
|
+
} else if (installed.revision !== entry.revision) {
|
|
181
|
+
await refreshInstalledRevision(projectRoot, entry.id, entry.revision);
|
|
182
|
+
changed.push({ id: entry.id, action: 'provenance-refreshed', version: entry.version });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const applicableIds = new Set(applicable.map((entry) => entry.id));
|
|
187
|
+
const catalogRules = new Map(
|
|
188
|
+
(catalog.entries ?? []).filter((entry) => entry.kind === 'rule').map((entry) => [entry.id, entry]),
|
|
189
|
+
);
|
|
190
|
+
for (const id of Object.keys(current.installed).filter((installedId) => !applicableIds.has(installedId))) {
|
|
191
|
+
const entry = catalogRules.get(id);
|
|
192
|
+
if (!entry) continue;
|
|
193
|
+
const prepared = await cachedManifest(source, entry, canonicalCheckRoot, checkerRuntimeRoot);
|
|
194
|
+
for (const copy of prepared.manifest.copies ?? []) {
|
|
195
|
+
const target = String(copy.target ?? copy.path ?? '');
|
|
196
|
+
if (target.startsWith('.agents/skills/')) allowedSkillFiles.add(target);
|
|
135
197
|
}
|
|
136
198
|
}
|
|
199
|
+
const removed = await cleanupCanonicalInstallState(projectRoot, catalog.entries ?? []);
|
|
137
200
|
await cleanupCanonicalSkillTree(projectRoot, allowedSkillFiles);
|
|
138
|
-
return { stack, applicable: applicable.length, changed };
|
|
201
|
+
return { stack, projectType, applicable: applicable.length, changed, removed };
|
|
139
202
|
}
|
|
140
203
|
|
|
141
|
-
export async function canonicalCheck(projectRoot, source) {
|
|
204
|
+
export async function canonicalCheck(projectRoot, source, options = {}) {
|
|
142
205
|
const current = await readInstalledState(projectRoot);
|
|
143
|
-
const { applicable, canonicalCheckRoot, checkerRuntimeRoot } = await canonicalContext(projectRoot, source, {
|
|
206
|
+
const { catalog, applicable, canonicalCheckRoot, checkerRuntimeRoot } = await canonicalContext(projectRoot, source, {
|
|
207
|
+
offline: false,
|
|
208
|
+
withCheckers: true,
|
|
209
|
+
refresh: options.refresh ?? false,
|
|
210
|
+
});
|
|
144
211
|
const byId = new Map(applicable.map((entry) => [entry.id, entry]));
|
|
212
|
+
const catalogRules = new Map(
|
|
213
|
+
(catalog.entries ?? []).filter((entry) => entry.kind === 'rule').map((entry) => [entry.id, entry]),
|
|
214
|
+
);
|
|
215
|
+
for (const id of Object.keys(current.installed)) {
|
|
216
|
+
const entry = catalogRules.get(id);
|
|
217
|
+
if (entry && !byId.has(id)) byId.set(id, entry);
|
|
218
|
+
}
|
|
145
219
|
const results = {};
|
|
220
|
+
const groups = new Map();
|
|
221
|
+
const executor = options.executor ?? execute;
|
|
146
222
|
let exitCode = 0;
|
|
147
223
|
for (const [id, installed] of Object.entries(current.installed).sort(([a], [b]) => a.localeCompare(b))) {
|
|
148
224
|
const entry = byId.get(id);
|
|
@@ -154,16 +230,109 @@ export async function canonicalCheck(projectRoot, source) {
|
|
|
154
230
|
exitCode = 1;
|
|
155
231
|
continue;
|
|
156
232
|
}
|
|
157
|
-
const
|
|
158
|
-
|
|
233
|
+
const key = prepared.checkerKey ?? `path:${prepared.checkerPath}:${JSON.stringify(prepared.checkerArgs ?? [])}`;
|
|
234
|
+
const group = groups.get(key) ?? {
|
|
235
|
+
checkerPath: prepared.checkerPath,
|
|
236
|
+
checkerArgs: prepared.checkerArgs ?? [],
|
|
237
|
+
ids: [],
|
|
238
|
+
};
|
|
239
|
+
group.ids.push(id);
|
|
240
|
+
groups.set(key, group);
|
|
241
|
+
}
|
|
242
|
+
for (const group of groups.values()) {
|
|
243
|
+
const execution = await executor('node', [group.checkerPath, ...group.checkerArgs], projectRoot);
|
|
244
|
+
const result = { status: execution.exitCode === 0 ? 'pass' : 'fail', ...execution };
|
|
245
|
+
for (const id of group.ids) results[id] = result;
|
|
159
246
|
if (execution.exitCode !== 0) exitCode = 1;
|
|
160
247
|
}
|
|
248
|
+
const orderedResults = Object.fromEntries(
|
|
249
|
+
Object.entries(results).sort(([a], [b]) => a.localeCompare(b)),
|
|
250
|
+
);
|
|
161
251
|
await writeChecksState(projectRoot, {
|
|
162
252
|
schemaVersion: 2,
|
|
163
253
|
checkedAt: new Date().toISOString(),
|
|
164
|
-
results: Object.fromEntries(Object.entries(
|
|
254
|
+
results: Object.fromEntries(Object.entries(orderedResults).map(([id, result]) => [id, { status: result.status }])),
|
|
165
255
|
});
|
|
166
|
-
return { exitCode, results };
|
|
256
|
+
return { exitCode, results: orderedResults };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
function rulesFlags(args) {
|
|
261
|
+
const result = { json: false, ids: [], categories: [], failed: false };
|
|
262
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
263
|
+
const arg = args[index];
|
|
264
|
+
if (arg === '--json') result.json = true;
|
|
265
|
+
else if (arg === '--failed') result.failed = true;
|
|
266
|
+
else if (arg === '--id' && args[index + 1]) result.ids.push(args[++index]);
|
|
267
|
+
else if (arg === '--category' && args[index + 1]) result.categories.push(args[++index]);
|
|
268
|
+
else throw new Error(`Unknown option: ${arg}`);
|
|
269
|
+
}
|
|
270
|
+
return result;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function aiMode(entry) {
|
|
274
|
+
if (entry.ai?.load) return entry.ai.load;
|
|
275
|
+
return 'failure-only';
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function ruleSummary(entry) {
|
|
279
|
+
if (entry.summary) return String(entry.summary).trim();
|
|
280
|
+
const content = String(entry.content ?? '').replace(/\r\n?/gu, '\n');
|
|
281
|
+
const intent = content.match(/(?:^|\n)## Intent\s*\n+([^#][\s\S]*?)(?=\n## |$)/u)?.[1]?.trim();
|
|
282
|
+
const source = intent || content
|
|
283
|
+
.split('\n')
|
|
284
|
+
.map((line) => line.trim())
|
|
285
|
+
.find((line) => line && !line.startsWith('#')) || entry.name || entry.id;
|
|
286
|
+
return source
|
|
287
|
+
.replace(/^\*\*Rule:\*\*\s*/u, '')
|
|
288
|
+
.replace(/\s+/gu, ' ')
|
|
289
|
+
.slice(0, 240)
|
|
290
|
+
.trim();
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function aiInstructionText() {
|
|
294
|
+
return [
|
|
295
|
+
'Specdest Devkit governs repository engineering rules.',
|
|
296
|
+
'Do not preload the full rule catalog.',
|
|
297
|
+
'Before changing code, use `specdest rules --category <category>` to discover compact relevant summaries, then `specdest rules --id <rule>` only for rules whose full guidance is needed.',
|
|
298
|
+
'Run the repository completion checks normally. If Devkit checks fail, use `specdest rules --failed` to load full guidance only for failed rules and fix the violation without weakening the rule.',
|
|
299
|
+
].join('\n');
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export async function canonicalRules(projectRoot, source, options = {}) {
|
|
303
|
+
const { stack, profile, applicable } = await canonicalContext(projectRoot, source);
|
|
304
|
+
let selected = applicable;
|
|
305
|
+
let detail = false;
|
|
306
|
+
if (options.ids?.length) {
|
|
307
|
+
const wanted = new Set(options.ids);
|
|
308
|
+
selected = selected.filter((entry) => wanted.has(entry.id));
|
|
309
|
+
detail = true;
|
|
310
|
+
} else if (options.categories?.length) {
|
|
311
|
+
const wanted = new Set(options.categories.map((value) => value.toLowerCase()));
|
|
312
|
+
selected = selected.filter((entry) => wanted.has(String(entry.category ?? '').toLowerCase()));
|
|
313
|
+
} else if (options.failed) {
|
|
314
|
+
const state = await readChecksState(projectRoot);
|
|
315
|
+
const failed = new Set(Object.entries(state.results ?? {}).filter(([, value]) => value.status === 'fail').map(([id]) => id));
|
|
316
|
+
selected = selected.filter((entry) => failed.has(entry.id));
|
|
317
|
+
detail = true;
|
|
318
|
+
} else {
|
|
319
|
+
selected = selected.filter((entry) => aiMode(entry) === 'always');
|
|
320
|
+
}
|
|
321
|
+
return {
|
|
322
|
+
stack,
|
|
323
|
+
profile,
|
|
324
|
+
detail,
|
|
325
|
+
rules: selected.map((entry) => ({
|
|
326
|
+
id: entry.id,
|
|
327
|
+
name: entry.name,
|
|
328
|
+
category: entry.category ?? null,
|
|
329
|
+
enforcement: entry.enforcement ?? 'guidance',
|
|
330
|
+
aiLoad: aiMode(entry),
|
|
331
|
+
summary: ruleSummary(entry),
|
|
332
|
+
composedOf: entry.composedOf ?? [],
|
|
333
|
+
...(detail ? { content: entry.content ?? '' } : {}),
|
|
334
|
+
})),
|
|
335
|
+
};
|
|
167
336
|
}
|
|
168
337
|
|
|
169
338
|
export async function canonicalDoctor(projectRoot, source) {
|
|
@@ -192,11 +361,30 @@ export function createCanonicalCommandHandlers(projectRoot = process.cwd(), opti
|
|
|
192
361
|
return 0;
|
|
193
362
|
},
|
|
194
363
|
check: async (args, io) => {
|
|
195
|
-
|
|
196
|
-
|
|
364
|
+
const refresh = args.length === 1 && args[0] === '--refresh';
|
|
365
|
+
if (args.length && !refresh) { io.stderr.write('Usage: specdest check [--refresh]\n'); return 2; }
|
|
366
|
+
const result = await canonicalCheck(projectRoot, source, { refresh });
|
|
197
367
|
for (const [id, check] of Object.entries(result.results)) io.stdout.write(`${check.status.toUpperCase()} ${id}\n`);
|
|
198
368
|
return result.exitCode;
|
|
199
369
|
},
|
|
370
|
+
rules: async (args, io) => {
|
|
371
|
+
const parsed = rulesFlags(args);
|
|
372
|
+
const result = await canonicalRules(projectRoot, source, parsed);
|
|
373
|
+
if (parsed.json) io.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
374
|
+
else {
|
|
375
|
+
for (const rule of result.rules) {
|
|
376
|
+
const body = result.detail ? rule.content.trim() : rule.summary;
|
|
377
|
+
const composition = rule.composedOf.length ? `\nComposed of: ${rule.composedOf.join(', ')}` : '';
|
|
378
|
+
io.stdout.write(`## ${rule.id} — ${rule.name}\n${body}${composition}\n\n`);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
return 0;
|
|
382
|
+
},
|
|
383
|
+
'ai-instruction': async (args, io) => {
|
|
384
|
+
if (args.length) { io.stderr.write('Usage: specdest ai-instruction\n'); return 2; }
|
|
385
|
+
io.stdout.write(`${aiInstructionText()}\n`);
|
|
386
|
+
return 0;
|
|
387
|
+
},
|
|
200
388
|
doctor: async (args, io) => {
|
|
201
389
|
if (args.length) { io.stderr.write('Usage: specdest doctor\n'); return 2; }
|
|
202
390
|
const result = await canonicalDoctor(projectRoot, source);
|
package/src/canonical-project.js
CHANGED
|
@@ -47,21 +47,32 @@ async function cacheProjectCopies(copies, sourceRoot, ruleRoot, label) {
|
|
|
47
47
|
return result;
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
function
|
|
50
|
+
function runtimeChecker(manifest, runtimeRoot) {
|
|
51
51
|
if (manifest?.check?.command?.[0] !== 'node') return null;
|
|
52
52
|
const target = String(manifest.check.command[1] ?? '');
|
|
53
|
-
|
|
53
|
+
if (!target.startsWith('.agents/skills/')) return null;
|
|
54
|
+
return {
|
|
55
|
+
path: join(runtimeRoot, target),
|
|
56
|
+
args: manifest.check.command.slice(2).map(String),
|
|
57
|
+
};
|
|
54
58
|
}
|
|
55
59
|
|
|
56
|
-
|
|
60
|
+
import { projectRuleApplies } from './project-targeting.js';
|
|
61
|
+
|
|
62
|
+
export function applicableCatalogEntries(entries, stack, profile) {
|
|
57
63
|
return entries
|
|
58
64
|
.filter((entry) => entry.kind === 'rule')
|
|
59
|
-
.filter((entry) =>
|
|
65
|
+
.filter((entry) => projectRuleApplies(entry, stack, profile, entries))
|
|
60
66
|
.sort((a, b) => a.id.localeCompare(b.id));
|
|
61
67
|
}
|
|
62
68
|
|
|
63
69
|
export async function prepareCachedManifest(entry, ruleRoot, canonicalCheckRoot, checkerRuntimeRoot = null) {
|
|
64
70
|
const raw = await readManifest(ruleRoot);
|
|
71
|
+
const checkerKey = raw.checker?.path
|
|
72
|
+
? `canonical:${String(raw.checker.path)}`
|
|
73
|
+
: raw.check?.command
|
|
74
|
+
? `command:${JSON.stringify(raw.check.command)}`
|
|
75
|
+
: null;
|
|
65
76
|
const runtimeRoot = join(ruleRoot, '.runtime');
|
|
66
77
|
await rm(runtimeRoot, { recursive: true, force: true });
|
|
67
78
|
await mkdir(runtimeRoot, { recursive: true });
|
|
@@ -72,8 +83,8 @@ export async function prepareCachedManifest(entry, ruleRoot, canonicalCheckRoot,
|
|
|
72
83
|
await materializeCopies(raw, ruleRoot, runtimeRoot);
|
|
73
84
|
|
|
74
85
|
const copies = await cacheProjectCopies(raw.copies ?? [], ruleRoot, ruleRoot, entry.id);
|
|
75
|
-
let
|
|
76
|
-
if (!
|
|
86
|
+
let checker = runtimeChecker(raw, runtimeRoot);
|
|
87
|
+
if (!checker && raw.checker?.path && canonicalCheckRoot) {
|
|
77
88
|
const relative = String(raw.checker.path).replace(/^canonical-check\//u, '');
|
|
78
89
|
const implementationRoot = dirname(join(canonicalCheckRoot, relative));
|
|
79
90
|
const implementationManifest = await readManifest(implementationRoot);
|
|
@@ -84,7 +95,7 @@ export async function prepareCachedManifest(entry, ruleRoot, canonicalCheckRoot,
|
|
|
84
95
|
ruleRoot,
|
|
85
96
|
basename(implementationRoot),
|
|
86
97
|
));
|
|
87
|
-
|
|
98
|
+
checker = runtimeChecker(implementationManifest, runtimeRoot);
|
|
88
99
|
}
|
|
89
100
|
|
|
90
101
|
const markdownSections = (raw.markdownSections ?? []).filter(
|
|
@@ -98,7 +109,12 @@ export async function prepareCachedManifest(entry, ruleRoot, canonicalCheckRoot,
|
|
|
98
109
|
...(entry.revision ? { revision: entry.revision } : {}),
|
|
99
110
|
copies: [...new Map(copies.map((copy) => [String(copy.target ?? copy.path ?? copy.source), copy])).values()],
|
|
100
111
|
markdownSections,
|
|
101
|
-
...(
|
|
112
|
+
...(checker ? { check: { command: ['specdest-cache', entry.id] } } : {}),
|
|
113
|
+
};
|
|
114
|
+
return {
|
|
115
|
+
manifest,
|
|
116
|
+
checkerPath: checker?.path ?? null,
|
|
117
|
+
checkerArgs: checker?.args ?? [],
|
|
118
|
+
checkerKey,
|
|
102
119
|
};
|
|
103
|
-
return { manifest, checkerPath };
|
|
104
120
|
}
|
package/src/canonical-source.js
CHANGED
|
@@ -121,7 +121,12 @@ export function createCanonicalSource(options = {}) {
|
|
|
121
121
|
const fetched = await fetchGitRevision(cacheRoot, options);
|
|
122
122
|
activeGitDir = fetched.gitDir;
|
|
123
123
|
revision = fetched.revision;
|
|
124
|
-
|
|
124
|
+
const rawCatalog = JSON.parse(await readGitFile(activeGitDir, revision, 'catalog.json'));
|
|
125
|
+
catalog = {
|
|
126
|
+
...rawCatalog,
|
|
127
|
+
repositoryRevision: revision,
|
|
128
|
+
entries: (rawCatalog.entries ?? []).map((entry) => ({ ...entry, revision })),
|
|
129
|
+
};
|
|
125
130
|
}
|
|
126
131
|
activeRevision = revision;
|
|
127
132
|
await mkdir(cacheRoot, { recursive: true });
|
|
@@ -202,10 +207,7 @@ export async function fetchGitHubModule(id, options = {}) {
|
|
|
202
207
|
return { files: await directoryFiles(root) };
|
|
203
208
|
}
|
|
204
209
|
|
|
205
|
-
|
|
206
|
-
let pkg = {};
|
|
207
|
-
try { pkg = JSON.parse(await readFile(join(projectRoot, 'package.json'), 'utf8')); } catch (error) { if (error?.code !== 'ENOENT') throw error; }
|
|
208
|
-
const deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
|
|
210
|
+
function stackFromDependencies(deps) {
|
|
209
211
|
const expo = Boolean(deps.expo);
|
|
210
212
|
const vite = Boolean(deps.vite || deps['@vitejs/plugin-react']);
|
|
211
213
|
const convex = Boolean(deps.convex);
|
|
@@ -216,3 +218,33 @@ export async function detectProjectStack(projectRoot) {
|
|
|
216
218
|
if (vite && supabase) return 'stack-vite-supabase';
|
|
217
219
|
return null;
|
|
218
220
|
}
|
|
221
|
+
|
|
222
|
+
async function readPackageDependencies(path) {
|
|
223
|
+
try {
|
|
224
|
+
const pkg = JSON.parse(await readFile(path, 'utf8'));
|
|
225
|
+
return { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (error?.code === 'ENOENT') return null;
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export async function detectProjectStack(projectRoot) {
|
|
233
|
+
const dependencySets = [];
|
|
234
|
+
const rootDeps = await readPackageDependencies(join(projectRoot, 'package.json'));
|
|
235
|
+
if (rootDeps) dependencySets.push(rootDeps);
|
|
236
|
+
for (const group of ['apps', 'packages']) {
|
|
237
|
+
let children = [];
|
|
238
|
+
try { children = await readdir(join(projectRoot, group), { withFileTypes: true }); }
|
|
239
|
+
catch (error) { if (error?.code !== 'ENOENT') throw error; }
|
|
240
|
+
for (const child of children.filter((entry) => entry.isDirectory())) {
|
|
241
|
+
const deps = await readPackageDependencies(join(projectRoot, group, child.name, 'package.json'));
|
|
242
|
+
if (deps) dependencySets.push(deps);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const detected = new Set(dependencySets.map(stackFromDependencies).filter(Boolean));
|
|
246
|
+
if (detected.size === 1) return [...detected][0];
|
|
247
|
+
if (detected.size > 1) throw new Error(`Multiple canonical stacks detected: ${[...detected].sort().join(', ')}`);
|
|
248
|
+
const combined = Object.assign({}, ...dependencySets);
|
|
249
|
+
return stackFromDependencies(combined);
|
|
250
|
+
}
|
package/src/cli.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { runCli } from './index.js';
|
|
2
|
+
import { createFuzzCommandHandler, runCli } from './index.js';
|
|
3
3
|
import { createCanonicalCommandHandlers } from './canonical-project-operations.js';
|
|
4
4
|
|
|
5
5
|
try {
|
|
6
|
-
const exitCode = await runCli(process.argv.slice(2), process,
|
|
6
|
+
const exitCode = await runCli(process.argv.slice(2), process, {
|
|
7
|
+
...createCanonicalCommandHandlers(),
|
|
8
|
+
fuzz: createFuzzCommandHandler(),
|
|
9
|
+
});
|
|
7
10
|
process.exitCode = exitCode;
|
|
8
11
|
} catch (error) {
|
|
9
12
|
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
package/src/fuzz.js
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { readdir, readFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join, relative, resolve } from 'node:path';
|
|
4
|
+
import { registerHooks } from 'node:module';
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
|
+
|
|
7
|
+
import fc from 'fast-check';
|
|
8
|
+
|
|
9
|
+
const DEFAULT_SUFFIXES = ['.input.schema.ts', '.output.schema.ts', '.form.schema.ts', '.callbackInput.schema.ts'];
|
|
10
|
+
const CONFIG_PATH = '.specdest/fuzz.json';
|
|
11
|
+
const DEFAULT_SEED = 20260914;
|
|
12
|
+
|
|
13
|
+
function schemaDef(schema) {
|
|
14
|
+
return schema?._zod?.def ?? schema?._def ?? schema?.def;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function schemaType(schema) {
|
|
18
|
+
return schemaDef(schema)?.type ?? schema?.type;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function isSchema(value) {
|
|
22
|
+
return value && typeof value.safeParse === 'function' && typeof schemaType(value) === 'string';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function unwrap(schema) {
|
|
26
|
+
const type = schemaType(schema);
|
|
27
|
+
if (type === 'optional' || type === 'nullable' || type === 'default' || type === 'catch') {
|
|
28
|
+
return unwrap(schemaDef(schema).innerType);
|
|
29
|
+
}
|
|
30
|
+
return schema;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function boundsFor(schema) {
|
|
34
|
+
const bounds = {
|
|
35
|
+
minLength: Number.isFinite(schema?.minLength) ? schema.minLength : undefined,
|
|
36
|
+
maxLength: Number.isFinite(schema?.maxLength) ? schema.maxLength : undefined,
|
|
37
|
+
minValue: Number.isFinite(schema?.minValue) ? schema.minValue : undefined,
|
|
38
|
+
maxValue: Number.isFinite(schema?.maxValue) ? schema.maxValue : undefined,
|
|
39
|
+
};
|
|
40
|
+
for (const check of schemaDef(schema)?.checks ?? []) {
|
|
41
|
+
const def = check?._zod?.def ?? check?.def;
|
|
42
|
+
if (def?.check === 'min_length') bounds.minLength = def.minimum;
|
|
43
|
+
if (def?.check === 'max_length') bounds.maxLength = def.maximum;
|
|
44
|
+
if (def?.check === 'greater_than' && def.inclusive) bounds.minValue = def.value;
|
|
45
|
+
if (def?.check === 'less_than' && def.inclusive) bounds.maxValue = def.value;
|
|
46
|
+
}
|
|
47
|
+
return bounds;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function zodArbitrary(schema) {
|
|
51
|
+
const type = schemaType(schema);
|
|
52
|
+
const def = schemaDef(schema);
|
|
53
|
+
if (type === 'optional') return fc.option(zodArbitrary(def.innerType), { nil: undefined });
|
|
54
|
+
if (type === 'nullable') return fc.option(zodArbitrary(def.innerType), { nil: null });
|
|
55
|
+
if (type === 'string') {
|
|
56
|
+
const { minLength = 0, maxLength = 32 } = boundsFor(schema);
|
|
57
|
+
return fc.string({ minLength, maxLength: Math.min(maxLength, 64) }).filter((value) => schema.safeParse(value).success);
|
|
58
|
+
}
|
|
59
|
+
if (type === 'number') {
|
|
60
|
+
const { minValue = -1000, maxValue = 1000 } = boundsFor(schema);
|
|
61
|
+
return fc.double({ min: minValue, max: maxValue, noNaN: true, noDefaultInfinity: true }).filter((value) => schema.safeParse(value).success);
|
|
62
|
+
}
|
|
63
|
+
if (type === 'boolean') return fc.boolean();
|
|
64
|
+
if (type === 'enum') return fc.constantFrom(...Object.values(def.entries));
|
|
65
|
+
if (type === 'array') {
|
|
66
|
+
const { minLength = 0, maxLength = 4 } = boundsFor(schema);
|
|
67
|
+
return fc.array(zodArbitrary(def.element), { minLength, maxLength: Math.min(maxLength, 8) }).filter((value) => schema.safeParse(value).success);
|
|
68
|
+
}
|
|
69
|
+
if (type === 'object') {
|
|
70
|
+
const shape = typeof def.shape === 'function' ? def.shape() : def.shape;
|
|
71
|
+
const shapeEntries = Object.entries(shape ?? {});
|
|
72
|
+
const entries = shapeEntries.map(([key, child]) => [key, zodArbitrary(child)]);
|
|
73
|
+
const requiredKeys = shapeEntries.filter(([, child]) => schemaType(child) !== 'optional').map(([key]) => key);
|
|
74
|
+
return fc.record(Object.fromEntries(entries), { requiredKeys })
|
|
75
|
+
.filter((value) => schema.safeParse(value).success);
|
|
76
|
+
}
|
|
77
|
+
throw new Error(`Unsupported Zod schema type: ${type ?? 'unknown'}`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function getAtPath(value, path) {
|
|
81
|
+
return path.reduce((current, key) => current?.[key], value);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function setAtPath(value, path, replacement, omit = false) {
|
|
85
|
+
if (!path.length) return replacement;
|
|
86
|
+
const clone = Array.isArray(value) ? [...value] : { ...value };
|
|
87
|
+
const [head, ...tail] = path;
|
|
88
|
+
if (!tail.length && omit) delete clone[head];
|
|
89
|
+
else clone[head] = setAtPath(value?.[head], tail, replacement, omit);
|
|
90
|
+
return clone;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function semanticCases(schema) {
|
|
94
|
+
const base = unwrap(schema);
|
|
95
|
+
const type = schemaType(base);
|
|
96
|
+
const bounds = boundsFor(base);
|
|
97
|
+
if (type === 'string') {
|
|
98
|
+
const cases = [['empty string', ''], ['single-space string', ' '], ['whitespace-only string', ' ']];
|
|
99
|
+
if (Number.isFinite(bounds.minLength)) cases.push(['minimum-length string', 'x'.repeat(bounds.minLength)]);
|
|
100
|
+
if (Number.isFinite(bounds.maxLength)) cases.push(['maximum-length string', 'x'.repeat(Math.min(bounds.maxLength, 128))]);
|
|
101
|
+
return cases;
|
|
102
|
+
}
|
|
103
|
+
if (type === 'number') {
|
|
104
|
+
const cases = [['zero', 0], ['NaN', Number.NaN]];
|
|
105
|
+
if (Number.isFinite(bounds.minValue)) cases.push(['minimum number', bounds.minValue]);
|
|
106
|
+
if (Number.isFinite(bounds.maxValue)) cases.push(['maximum number', bounds.maxValue]);
|
|
107
|
+
return cases;
|
|
108
|
+
}
|
|
109
|
+
if (type === 'boolean') return [['false', false]];
|
|
110
|
+
if (type === 'array') return [['empty array', []], ['array containing null', [null]], ['array containing undefined', [undefined]]];
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function collectLeaves(schema, path = []) {
|
|
115
|
+
const def = schemaDef(schema);
|
|
116
|
+
const type = schemaType(schema);
|
|
117
|
+
if (type === 'optional' || type === 'nullable') return collectLeaves(def.innerType, path).map((leaf) => ({ ...leaf, wrappers: [type, ...(leaf.wrappers ?? [])] }));
|
|
118
|
+
if (type === 'object') {
|
|
119
|
+
const shape = typeof def.shape === 'function' ? def.shape() : def.shape;
|
|
120
|
+
return Object.entries(shape ?? {}).flatMap(([key, child]) => collectLeaves(child, [...path, key]));
|
|
121
|
+
}
|
|
122
|
+
return [{ path, schema, wrappers: [] }];
|
|
123
|
+
}
|
|
124
|
+
function semanticConcern(leaf, label, accepted) {
|
|
125
|
+
if (!accepted) return null;
|
|
126
|
+
if (schemaType(unwrap(leaf.schema)) === 'string' && /empty|space|whitespace/u.test(label)) {
|
|
127
|
+
return 'empty/whitespace strings are accepted';
|
|
128
|
+
}
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function amplifySchema(schema, sample) {
|
|
133
|
+
const cases = [];
|
|
134
|
+
for (const leaf of collectLeaves(schema)) {
|
|
135
|
+
for (const [label, replacement] of semanticCases(leaf.schema)) {
|
|
136
|
+
const value = setAtPath(sample, leaf.path, replacement);
|
|
137
|
+
const accepted = schema.safeParse(value).success;
|
|
138
|
+
cases.push({ path: leaf.path.join('.'), label, value: replacement, accepted, concern: semanticConcern(leaf, label, accepted) });
|
|
139
|
+
}
|
|
140
|
+
if (schemaType(unwrap(leaf.schema)) === 'array') {
|
|
141
|
+
const current = getAtPath(sample, leaf.path);
|
|
142
|
+
if (Array.isArray(current) && current.length) {
|
|
143
|
+
const arrayCases = [['array item removal', current.slice(1)], ['duplicate array item', [current[0], ...current]]];
|
|
144
|
+
if (current.length > 1) arrayCases.push(['array reordering', [...current].reverse()]);
|
|
145
|
+
for (const [label, replacement] of arrayCases) {
|
|
146
|
+
const value = setAtPath(sample, leaf.path, replacement);
|
|
147
|
+
cases.push({ path: leaf.path.join('.'), label, value: replacement, accepted: schema.safeParse(value).success, concern: null });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (leaf.path.length) {
|
|
152
|
+
for (const [label, replacement, omit] of [['null', null, false], ['undefined', undefined, false], ['omitted property', undefined, true]]) {
|
|
153
|
+
const value = setAtPath(sample, leaf.path, replacement, omit);
|
|
154
|
+
cases.push({ path: leaf.path.join('.'), label, value: replacement, accepted: schema.safeParse(value).success, concern: null });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return cases;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function fuzzSchema(schema, { seed = DEFAULT_SEED, numRuns = 50 } = {}) {
|
|
162
|
+
let arbitrary;
|
|
163
|
+
try {
|
|
164
|
+
arbitrary = zodArbitrary(schema);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
return { status: 'unsupported', reason: error.message };
|
|
167
|
+
}
|
|
168
|
+
let lastCases = [];
|
|
169
|
+
const property = fc.property(arbitrary, (sample) => {
|
|
170
|
+
lastCases = amplifySchema(schema, sample);
|
|
171
|
+
return !lastCases.some((item) => item.concern);
|
|
172
|
+
});
|
|
173
|
+
const result = fc.check(property, { seed, numRuns });
|
|
174
|
+
if (!result.failed) return { status: 'pass', seed, cases: lastCases };
|
|
175
|
+
const sample = result.counterexample?.[0];
|
|
176
|
+
const cases = sample === undefined ? lastCases : amplifySchema(schema, sample);
|
|
177
|
+
return {
|
|
178
|
+
status: 'fail',
|
|
179
|
+
seed,
|
|
180
|
+
path: result.counterexamplePath,
|
|
181
|
+
counterexample: cases.find((item) => item.concern),
|
|
182
|
+
cases,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function walk(dir) {
|
|
187
|
+
const found = [];
|
|
188
|
+
let entries = [];
|
|
189
|
+
try { entries = await readdir(dir, { withFileTypes: true }); } catch { return found; }
|
|
190
|
+
for (const entry of entries) {
|
|
191
|
+
if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue;
|
|
192
|
+
const path = join(dir, entry.name);
|
|
193
|
+
if (entry.isDirectory()) found.push(...await walk(path));
|
|
194
|
+
else if (DEFAULT_SUFFIXES.some((suffix) => entry.name.endsWith(suffix))) found.push(path);
|
|
195
|
+
}
|
|
196
|
+
return found;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function readConfig(projectRoot) {
|
|
200
|
+
try {
|
|
201
|
+
const text = await readFile(join(projectRoot, CONFIG_PATH), 'utf8');
|
|
202
|
+
const config = JSON.parse(text);
|
|
203
|
+
if (config.schemaVersion !== 1 || !Array.isArray(config.targets)) throw new Error(`${CONFIG_PATH} must use schemaVersion 1 and a targets array`);
|
|
204
|
+
return config;
|
|
205
|
+
} catch (error) {
|
|
206
|
+
if (error?.code === 'ENOENT') return null;
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function discoverFuzzTargets(projectRoot) {
|
|
212
|
+
const config = await readConfig(projectRoot);
|
|
213
|
+
if (config) return config.targets.map((target) => ({ module: resolve(projectRoot, target.module), exports: target.exports ?? null }));
|
|
214
|
+
const files = [...await walk(join(projectRoot, 'src')), ...await walk(join(projectRoot, 'supabase', 'functions'))];
|
|
215
|
+
return files.map((module) => ({ module, exports: null }));
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function resolveProjectSpecifier(specifier, parentURL, projectRoot) {
|
|
219
|
+
let base;
|
|
220
|
+
if (specifier.startsWith('@/')) base = resolve(projectRoot, 'src', specifier.slice(2));
|
|
221
|
+
else if ((specifier.startsWith('./') || specifier.startsWith('../')) && parentURL?.startsWith('file:')) {
|
|
222
|
+
base = resolve(dirname(fileURLToPath(parentURL)), specifier);
|
|
223
|
+
} else return null;
|
|
224
|
+
const candidates = [base, ...['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].map((ext) => `${base}${ext}`),
|
|
225
|
+
...['.ts', '.tsx', '.js', '.jsx'].map((ext) => join(base, `index${ext}`))];
|
|
226
|
+
return candidates.find((candidate) => existsSync(candidate)) ?? null;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function loadTarget(target, projectRoot) {
|
|
230
|
+
const hooks = registerHooks({
|
|
231
|
+
resolve(specifier, context, nextResolve) {
|
|
232
|
+
const resolved = resolveProjectSpecifier(specifier, context.parentURL, projectRoot);
|
|
233
|
+
return resolved ? nextResolve(pathToFileURL(resolved).href, context) : nextResolve(specifier, context);
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
try {
|
|
237
|
+
const loaded = await import(pathToFileURL(target.module).href);
|
|
238
|
+
return Object.entries(loaded)
|
|
239
|
+
.filter(([name, value]) => (!target.exports || target.exports.includes(name)) && isSchema(value))
|
|
240
|
+
.map(([name, schema]) => ({ name, schema }));
|
|
241
|
+
} finally {
|
|
242
|
+
hooks.deregister();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
function formatValue(value) {
|
|
246
|
+
if (value === undefined) return 'undefined';
|
|
247
|
+
if (typeof value === 'number' && Number.isNaN(value)) return 'NaN';
|
|
248
|
+
return JSON.stringify(value);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export async function runFuzz(projectRoot, { seed = DEFAULT_SEED } = {}) {
|
|
252
|
+
const targets = await discoverFuzzTargets(projectRoot);
|
|
253
|
+
const results = [];
|
|
254
|
+
for (const target of targets) {
|
|
255
|
+
let schemas;
|
|
256
|
+
try {
|
|
257
|
+
schemas = await loadTarget(target, projectRoot);
|
|
258
|
+
} catch (error) {
|
|
259
|
+
results.push({ status: 'unsupported', module: target.module, name: '*', reason: `unable to load module: ${error.message}` });
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
if (!schemas.length) {
|
|
263
|
+
results.push({ status: 'unsupported', module: target.module, name: '*', reason: 'no exported Zod schema found' });
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
for (const { name, schema } of schemas) results.push({ module: target.module, name, ...fuzzSchema(schema, { seed }) });
|
|
267
|
+
}
|
|
268
|
+
return { seed, targets, results, failed: results.filter((item) => item.status === 'fail'), unsupported: results.filter((item) => item.status === 'unsupported') };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function createFuzzCommandHandler(projectRoot = process.cwd()) {
|
|
272
|
+
return async (args, io) => {
|
|
273
|
+
if (args.length) { io.stderr.write('Usage: specdest fuzz\n'); return 2; }
|
|
274
|
+
const result = await runFuzz(projectRoot);
|
|
275
|
+
for (const item of result.failed) {
|
|
276
|
+
const counterexample = item.counterexample;
|
|
277
|
+
const label = `${item.name}${counterexample?.path ? `.${counterexample.path}` : ''}`;
|
|
278
|
+
io.stderr.write(`FAIL ${label}\n\n`);
|
|
279
|
+
io.stderr.write(`Unexpected behavior for amplified value:\n${formatValue(counterexample?.value)}\n\n`);
|
|
280
|
+
io.stderr.write(`Related semantic concern:\n${counterexample?.concern ?? 'fuzz property failed'}\n\n`);
|
|
281
|
+
io.stderr.write(`Reproduce: seed=${item.seed}${item.path ? ` path=${item.path}` : ''}\n`);
|
|
282
|
+
io.stderr.write(`Module: ${relative(projectRoot, item.module)}\n\n`);
|
|
283
|
+
}
|
|
284
|
+
for (const item of result.unsupported) io.stderr.write(`SKIP ${relative(projectRoot, item.module)} ${item.name}: ${item.reason}\n`);
|
|
285
|
+
if (!result.results.length) io.stdout.write('Fuzz: no contract targets found.\n');
|
|
286
|
+
else if (!result.failed.length) io.stdout.write(`Fuzz: ${result.results.length - result.unsupported.length} passed; ${result.unsupported.length} skipped.\n`);
|
|
287
|
+
return result.failed.length ? 1 : 0;
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export const FUZZ_DEFAULT_SEED = DEFAULT_SEED;
|
package/src/git-catalog.js
CHANGED
|
@@ -34,6 +34,20 @@ function title(content, id) {
|
|
|
34
34
|
return content.match(/^#\s+(.+)$/mu)?.[1]?.trim() || id;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
function summary(content, fallback) {
|
|
38
|
+
const normalized = String(content ?? '').replace(/\r\n?/gu, '\n');
|
|
39
|
+
const intent = normalized.match(/(?:^|\n)## Intent\s*\n+([^#][\s\S]*?)(?=\n## |$)/u)?.[1]?.trim();
|
|
40
|
+
const source = intent || normalized
|
|
41
|
+
.split('\n')
|
|
42
|
+
.map((line) => line.trim())
|
|
43
|
+
.find((line) => line && !line.startsWith('#')) || fallback;
|
|
44
|
+
return source
|
|
45
|
+
.replace(/^\*\*Rule:\*\*\s*/u, '')
|
|
46
|
+
.replace(/\s+/gu, ' ')
|
|
47
|
+
.slice(0, 240)
|
|
48
|
+
.trim();
|
|
49
|
+
}
|
|
50
|
+
|
|
37
51
|
function canonicalVersion(manifest) {
|
|
38
52
|
const version = String(manifest.version ?? '');
|
|
39
53
|
if (!/^\d+\.\d+\.\d+$/u.test(version)) {
|
|
@@ -53,6 +67,26 @@ function notApplicableRuleIds(manifest) {
|
|
|
53
67
|
return [...new Set(manifest.notApplicableRuleIds.map(String))].sort();
|
|
54
68
|
}
|
|
55
69
|
|
|
70
|
+
function projectProfiles(manifest) {
|
|
71
|
+
if (!manifest.projectProfiles) return undefined;
|
|
72
|
+
if (typeof manifest.projectProfiles !== 'object' || Array.isArray(manifest.projectProfiles)) {
|
|
73
|
+
throw new Error(`Invalid projectProfiles: ${manifest.id}`);
|
|
74
|
+
}
|
|
75
|
+
return Object.fromEntries(Object.entries(manifest.projectProfiles).sort(([a], [b]) => a.localeCompare(b)).map(
|
|
76
|
+
([name, definition]) => {
|
|
77
|
+
if (!definition || !Array.isArray(definition.ruleIds) || definition.ruleIds.length === 0) {
|
|
78
|
+
throw new Error(`Invalid project profile: ${manifest.id}:${name}`);
|
|
79
|
+
}
|
|
80
|
+
return [name, { ruleIds: [...new Set(definition.ruleIds.map(String))].sort() }];
|
|
81
|
+
},
|
|
82
|
+
));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function stringList(value) {
|
|
86
|
+
if (!Array.isArray(value) || value.length === 0) return undefined;
|
|
87
|
+
return [...new Set(value.map(String))].sort();
|
|
88
|
+
}
|
|
89
|
+
|
|
56
90
|
function applicableStacks(manifest) {
|
|
57
91
|
if (manifest.scope !== 'Stack-specific') return undefined;
|
|
58
92
|
if (!Array.isArray(manifest.applicableStacks) || manifest.applicableStacks.length === 0) {
|
|
@@ -65,7 +99,7 @@ export async function buildGitCatalog({ modulesRoot, repositoryRevision = 'worki
|
|
|
65
99
|
const directories = (await readdir(modulesRoot, { withFileTypes: true }))
|
|
66
100
|
.filter((entry) => entry.isDirectory())
|
|
67
101
|
.sort((a, b) => a.name.localeCompare(b.name));
|
|
68
|
-
const
|
|
102
|
+
const modules = [];
|
|
69
103
|
for (const directory of directories) {
|
|
70
104
|
const root = join(modulesRoot, directory.name);
|
|
71
105
|
const files = await moduleFiles(root);
|
|
@@ -73,7 +107,14 @@ export async function buildGitCatalog({ modulesRoot, repositoryRevision = 'worki
|
|
|
73
107
|
if (!manifestFile) throw new Error(`Missing manifest.json: ${directory.name}`);
|
|
74
108
|
const manifest = JSON.parse(manifestFile.content);
|
|
75
109
|
if (manifest.id !== directory.name) throw new Error(`Module id/path mismatch: ${directory.name}`);
|
|
76
|
-
|
|
110
|
+
modules.push({ files, manifest, ownContentHash: sha256(JSON.stringify(files)) });
|
|
111
|
+
}
|
|
112
|
+
const canonicalCheckHash = modules.find(({ manifest }) => manifest.id === 'canonical-check')?.ownContentHash ?? null;
|
|
113
|
+
const entries = [];
|
|
114
|
+
for (const { files, manifest, ownContentHash } of modules) {
|
|
115
|
+
const contentHash = manifest.checker?.path && canonicalCheckHash
|
|
116
|
+
? sha256(JSON.stringify({ ownContentHash, canonicalCheckHash }))
|
|
117
|
+
: ownContentHash;
|
|
77
118
|
const guidance = files.find((file) => /(^|\/)rule\.md$/u.test(file.path) || /(^|\/)SKILL\.md$/u.test(file.path))?.content ?? '';
|
|
78
119
|
const kind = catalogKind(manifest);
|
|
79
120
|
entries.push({
|
|
@@ -82,6 +123,9 @@ export async function buildGitCatalog({ modulesRoot, repositoryRevision = 'worki
|
|
|
82
123
|
version: canonicalVersion(manifest),
|
|
83
124
|
name: title(guidance, manifest.id),
|
|
84
125
|
content: guidance,
|
|
126
|
+
...(kind === 'rule' ? { summary: summary(guidance, manifest.name ?? manifest.id) } : {}),
|
|
127
|
+
...(kind === 'rule' && manifest.category ? { category: String(manifest.category) } : {}),
|
|
128
|
+
...(kind === 'rule' && manifest.scope ? { scope: String(manifest.scope) } : {}),
|
|
85
129
|
group: kind === 'rule' ? 'Rules' : 'Modules',
|
|
86
130
|
order: entries.length + 1,
|
|
87
131
|
source: 'private-devkit-git',
|
|
@@ -90,9 +134,16 @@ export async function buildGitCatalog({ modulesRoot, repositoryRevision = 'worki
|
|
|
90
134
|
...(kind === 'rule' ? { legacyInstalledIds: legacyImplementationIds(manifest) } : {}),
|
|
91
135
|
...(kind === 'rule' ? { enforcement: String(manifest.enforcement ?? 'guidance') } : {}),
|
|
92
136
|
...(kind === 'rule' && applicableStacks(manifest) ? { applicableStacks: applicableStacks(manifest) } : {}),
|
|
137
|
+
...(kind === 'rule' && stringList(manifest.requiredCapabilities) ? { requiredCapabilities: stringList(manifest.requiredCapabilities) } : {}),
|
|
138
|
+
...(kind === 'rule' && manifest.ai ? { ai: manifest.ai } : {}),
|
|
139
|
+
...(kind === 'rule' && manifest.verification ? { verification: manifest.verification } : {}),
|
|
140
|
+
...(kind === 'rule' && stringList(manifest.composedOf) ? { composedOf: stringList(manifest.composedOf) } : {}),
|
|
93
141
|
...(kind === 'module' && notApplicableRuleIds(manifest)
|
|
94
142
|
? { notApplicableRuleIds: notApplicableRuleIds(manifest) }
|
|
95
143
|
: {}),
|
|
144
|
+
...(kind === 'module' && projectProfiles(manifest)
|
|
145
|
+
? { projectProfiles: projectProfiles(manifest) }
|
|
146
|
+
: {}),
|
|
96
147
|
});
|
|
97
148
|
}
|
|
98
149
|
const ruleIds = new Set(entries.filter((entry) => entry.kind === 'rule').map((entry) => entry.id));
|
|
@@ -100,6 +151,27 @@ export async function buildGitCatalog({ modulesRoot, repositoryRevision = 'worki
|
|
|
100
151
|
for (const ruleId of entry.notApplicableRuleIds ?? []) {
|
|
101
152
|
if (!ruleIds.has(ruleId)) throw new Error(`Unknown not-applicable rule: ${entry.id}:${ruleId}`);
|
|
102
153
|
}
|
|
154
|
+
for (const [profileName, definition] of Object.entries(entry.projectProfiles ?? {})) {
|
|
155
|
+
for (const ruleId of definition.ruleIds) {
|
|
156
|
+
if (!ruleIds.has(ruleId)) throw new Error(`Unknown project-profile rule: ${entry.id}:${profileName}:${ruleId}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
for (const childId of entry.composedOf ?? []) {
|
|
160
|
+
if (!ruleIds.has(childId)) throw new Error(`Unknown composed rule: ${entry.id}:${childId}`);
|
|
161
|
+
if (childId === entry.id) throw new Error(`Rule cannot compose itself: ${entry.id}`);
|
|
162
|
+
}
|
|
103
163
|
}
|
|
164
|
+
const composition = new Map(entries.filter((entry) => entry.kind === 'rule').map((entry) => [entry.id, entry.composedOf ?? []]));
|
|
165
|
+
const visiting = new Set();
|
|
166
|
+
const visited = new Set();
|
|
167
|
+
const visit = (id) => {
|
|
168
|
+
if (visiting.has(id)) throw new Error(`Rule composition cycle: ${id}`);
|
|
169
|
+
if (visited.has(id)) return;
|
|
170
|
+
visiting.add(id);
|
|
171
|
+
for (const childId of composition.get(id) ?? []) visit(childId);
|
|
172
|
+
visiting.delete(id);
|
|
173
|
+
visited.add(id);
|
|
174
|
+
};
|
|
175
|
+
for (const id of composition.keys()) visit(id);
|
|
104
176
|
return { schemaVersion: 1, package: { name: '@specdest/devkit', version: repositoryRevision }, entries };
|
|
105
177
|
}
|
package/src/index.js
CHANGED
|
@@ -4,14 +4,16 @@ export * from './canonical-project.js';
|
|
|
4
4
|
export * from './canonical-project-operations.js';
|
|
5
5
|
export * from './installer-primitives.js';
|
|
6
6
|
export * from './project-operations.js';
|
|
7
|
+
export * from './rule-profile.js';
|
|
7
8
|
export * from './remote-installer.js';
|
|
8
9
|
export * from './setup-requirements.js';
|
|
9
10
|
export * from './shared-file.js';
|
|
10
11
|
export * from './sync-core.js';
|
|
12
|
+
export * from './fuzz.js';
|
|
11
13
|
|
|
12
|
-
export const COMMAND_NAMES = ['status', 'sync', 'check', 'doctor'];
|
|
14
|
+
export const COMMAND_NAMES = ['status', 'sync', 'check', 'rules', 'ai-instruction', 'doctor', 'fuzz'];
|
|
13
15
|
|
|
14
|
-
const HELP = `Usage: specdest <command> [options]\n\nCommands:\n status [--refresh] [--json] Show canonical applicability/install status\n sync Refresh catalog/cache and install/update applicable rules\n check
|
|
16
|
+
const HELP = `Usage: specdest <command> [options]\n\nCommands:\n status [--refresh] [--json] Show canonical applicability/install status\n sync Refresh catalog/cache and install/update applicable rules\n check [--refresh] Run installed rule checks; optionally refresh canonical cache first\n rules [options] Load applicable rule guidance for AI/task context\n ai-instruction Print the minimal AI bootstrap instruction\n doctor Diagnose project/cache setup\n fuzz Dynamically fuzz Zod contract semantics\n`;
|
|
15
17
|
|
|
16
18
|
export async function runCli(argv, io = process, handlers = {}) {
|
|
17
19
|
const [command, ...args] = argv;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { EMPTY_RULE_PROFILE } from './rule-profile.js';
|
|
2
|
+
|
|
3
|
+
export const PROJECT_TYPES = Object.freeze([
|
|
4
|
+
'product',
|
|
5
|
+
'static-site',
|
|
6
|
+
'tooling',
|
|
7
|
+
'backend',
|
|
8
|
+
'monorepo',
|
|
9
|
+
'generic',
|
|
10
|
+
]);
|
|
11
|
+
|
|
12
|
+
export function resolveProjectType(stack, profile = EMPTY_RULE_PROFILE) {
|
|
13
|
+
return profile.projectType ?? (stack ? 'product' : 'generic');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function profileDefinition(entries, projectType) {
|
|
17
|
+
if (projectType === 'product') return null;
|
|
18
|
+
const module = entries.find(
|
|
19
|
+
(entry) => entry.kind === 'module' && entry.id === 'project-profiles',
|
|
20
|
+
);
|
|
21
|
+
const definition = module?.projectProfiles?.[projectType];
|
|
22
|
+
if (!definition) throw new Error(`Canonical project profile not found: ${projectType}`);
|
|
23
|
+
return definition;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function capabilitySatisfied(entry, profile) {
|
|
27
|
+
const capabilities = new Set(profile.capabilities ?? []);
|
|
28
|
+
return !entry.requiredCapabilities?.some((capability) => !capabilities.has(capability));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function projectRuleApplies(entry, stack, profile = EMPTY_RULE_PROFILE, entries = []) {
|
|
32
|
+
const included = new Set(profile.include ?? []);
|
|
33
|
+
const excluded = new Set((profile.exclude ?? []).map((item) => item.id));
|
|
34
|
+
if (excluded.has(entry.id)) return false;
|
|
35
|
+
if (included.has(entry.id)) return true;
|
|
36
|
+
|
|
37
|
+
const projectType = resolveProjectType(stack, profile);
|
|
38
|
+
if (projectType === 'product') {
|
|
39
|
+
if (entry.applicableStacks?.length && (!stack || !entry.applicableStacks.includes(stack))) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
return capabilitySatisfied(entry, profile);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const definition = profileDefinition(entries, projectType);
|
|
46
|
+
if (!definition.ruleIds.includes(entry.id)) return false;
|
|
47
|
+
return capabilitySatisfied(entry, profile);
|
|
48
|
+
}
|
package/src/remote-installer.js
CHANGED
|
@@ -4,6 +4,7 @@ import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:
|
|
|
4
4
|
import { dirname, isAbsolute, resolve, sep } from 'node:path';
|
|
5
5
|
|
|
6
6
|
import { removeMarkdownSection, resolveProjectPath, upsertMarkdownSection } from './installer-primitives.js';
|
|
7
|
+
import { formatJsonState } from './sync-core.js';
|
|
7
8
|
|
|
8
9
|
const INSTALLED_PATH = '.specdest/installed.json';
|
|
9
10
|
const STATE_PATH = '.specdest/state.json';
|
|
@@ -40,7 +41,7 @@ async function writeJsonState(root, relativePath, state) {
|
|
|
40
41
|
const target = resolveProjectPath(root, relativePath);
|
|
41
42
|
await mkdir(dirname(target), { recursive: true });
|
|
42
43
|
const temp = `${target}.${process.pid}.tmp`;
|
|
43
|
-
await writeFile(temp,
|
|
44
|
+
await writeFile(temp, formatJsonState(state), 'utf8');
|
|
44
45
|
await rename(temp, target);
|
|
45
46
|
}
|
|
46
47
|
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
export const RULE_PROFILE_RELATIVE_PATH = '.specdest/rules.json';
|
|
5
|
+
export const EMPTY_RULE_PROFILE = Object.freeze({
|
|
6
|
+
schemaVersion: 1,
|
|
7
|
+
projectType: null,
|
|
8
|
+
capabilities: [],
|
|
9
|
+
include: [],
|
|
10
|
+
exclude: [],
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
function uniqueStrings(values, label) {
|
|
14
|
+
if (!Array.isArray(values ?? [])) throw new Error(`Invalid ${label}`);
|
|
15
|
+
return [...new Set((values ?? []).map(String).map((value) => value.trim()).filter(Boolean))].sort();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function validateRuleProfile(profile) {
|
|
19
|
+
if (!profile || typeof profile !== 'object' || Array.isArray(profile) || profile.schemaVersion !== 1) {
|
|
20
|
+
throw new Error('Invalid .specdest/rules.json profile');
|
|
21
|
+
}
|
|
22
|
+
const projectType = profile.projectType == null ? null : String(profile.projectType).trim();
|
|
23
|
+
if (profile.projectType != null && !projectType) throw new Error('Invalid rule profile projectType');
|
|
24
|
+
const capabilities = uniqueStrings(profile.capabilities, 'rule profile capabilities');
|
|
25
|
+
const include = uniqueStrings(profile.include, 'rule profile include');
|
|
26
|
+
if (!Array.isArray(profile.exclude ?? [])) throw new Error('Invalid rule profile exclude');
|
|
27
|
+
const exclude = (profile.exclude ?? []).map((item) => {
|
|
28
|
+
if (!item || typeof item !== 'object' || !String(item.id ?? '').trim() || !String(item.reason ?? '').trim()) {
|
|
29
|
+
throw new Error('Rule exclusions require both id and non-empty reason');
|
|
30
|
+
}
|
|
31
|
+
return { id: String(item.id).trim(), reason: String(item.reason).trim() };
|
|
32
|
+
}).sort((a, b) => a.id.localeCompare(b.id));
|
|
33
|
+
return { schemaVersion: 1, projectType, capabilities, include, exclude };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function readRuleProfile(projectRoot) {
|
|
37
|
+
try {
|
|
38
|
+
const raw = JSON.parse(await readFile(join(projectRoot, RULE_PROFILE_RELATIVE_PATH), 'utf8'));
|
|
39
|
+
return validateRuleProfile(raw);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (error?.code === 'ENOENT') return { ...EMPTY_RULE_PROFILE, capabilities: [], include: [], exclude: [] };
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function ruleApplies(entry, stack, profile = EMPTY_RULE_PROFILE) {
|
|
47
|
+
const included = new Set(profile.include ?? []);
|
|
48
|
+
const excluded = new Set((profile.exclude ?? []).map((item) => item.id));
|
|
49
|
+
if (excluded.has(entry.id)) return false;
|
|
50
|
+
if (included.has(entry.id)) return true;
|
|
51
|
+
if (entry.applicableStacks?.length && (!stack || !entry.applicableStacks.includes(stack))) return false;
|
|
52
|
+
const capabilities = new Set(profile.capabilities ?? []);
|
|
53
|
+
if (entry.requiredCapabilities?.some((capability) => !capabilities.has(capability))) return false;
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function assertKnownRuleOverrides(entries, profile) {
|
|
58
|
+
const ids = new Set(entries.filter((entry) => entry.kind === 'rule').map((entry) => entry.id));
|
|
59
|
+
for (const id of profile.include ?? []) if (!ids.has(id)) throw new Error(`Unknown included rule: ${id}`);
|
|
60
|
+
for (const item of profile.exclude ?? []) if (!ids.has(item.id)) throw new Error(`Unknown excluded rule: ${item.id}`);
|
|
61
|
+
}
|
package/src/sync-core.js
CHANGED
|
@@ -33,10 +33,42 @@ async function readJsonOrDefault(filePath, fallback) {
|
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
+
const JSON_INDENT = 2;
|
|
37
|
+
const JSON_LINE_WIDTH = 100;
|
|
38
|
+
|
|
39
|
+
function isOmittedJsonValue(value) {
|
|
40
|
+
return value === undefined || ['function', 'symbol'].includes(typeof value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function formatJsonValue(value, depth = 0, { arrayItem = false } = {}) {
|
|
44
|
+
if (isOmittedJsonValue(value)) return arrayItem ? 'null' : undefined;
|
|
45
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
|
46
|
+
const indent = ' '.repeat(depth * JSON_INDENT);
|
|
47
|
+
const childIndent = ' '.repeat((depth + 1) * JSON_INDENT);
|
|
48
|
+
if (Array.isArray(value)) {
|
|
49
|
+
if (!value.length) return '[]';
|
|
50
|
+
const primitive = value.every(
|
|
51
|
+
(item) => isOmittedJsonValue(item) || item === null || ['string', 'number', 'boolean'].includes(typeof item),
|
|
52
|
+
);
|
|
53
|
+
if (primitive) {
|
|
54
|
+
const inline = `[${value.map((item) => formatJsonValue(item, depth + 1, { arrayItem: true })).join(', ')}]`;
|
|
55
|
+
if (indent.length + inline.length <= JSON_LINE_WIDTH) return inline;
|
|
56
|
+
}
|
|
57
|
+
return `[\n${value.map((item) => `${childIndent}${formatJsonValue(item, depth + 1, { arrayItem: true })}`).join(',\n')}\n${indent}]`;
|
|
58
|
+
}
|
|
59
|
+
const entries = Object.entries(value).filter(([, item]) => !isOmittedJsonValue(item));
|
|
60
|
+
if (!entries.length) return '{}';
|
|
61
|
+
return `{\n${entries.map(([key, item]) => `${childIndent}${JSON.stringify(key)}: ${formatJsonValue(item, depth + 1)}`).join(',\n')}\n${indent}}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function formatJsonState(value) {
|
|
65
|
+
return `${formatJsonValue(value)}\n`;
|
|
66
|
+
}
|
|
67
|
+
|
|
36
68
|
async function writeJsonAtomic(filePath, value) {
|
|
37
69
|
await mkdir(dirname(filePath), { recursive: true });
|
|
38
70
|
const temp = `${filePath}.${process.pid}.tmp`;
|
|
39
|
-
await writeFile(temp,
|
|
71
|
+
await writeFile(temp, formatJsonState(value), 'utf8');
|
|
40
72
|
await rename(temp, filePath);
|
|
41
73
|
}
|
|
42
74
|
|
|
@@ -70,11 +102,7 @@ export async function readInstalledState(projectRoot) {
|
|
|
70
102
|
}
|
|
71
103
|
|
|
72
104
|
function formatInstalledState(state) {
|
|
73
|
-
|
|
74
|
-
.split('\n')
|
|
75
|
-
.map((line, index) => index === 0 ? line : ` ${line}`)
|
|
76
|
-
.join('\n');
|
|
77
|
-
return `{\n "schemaVersion": ${STATE_SCHEMA_VERSION},\n "requested": ${JSON.stringify(state.requested)},\n "installed": ${installed}\n}\n`;
|
|
105
|
+
return formatJsonState(state);
|
|
78
106
|
}
|
|
79
107
|
|
|
80
108
|
export async function writeInstalledState(projectRoot, state) {
|