@specdest/devkit 0.3.4 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -2
- package/package.json +11 -4
- package/src/canonical-project-operations.js +178 -18
- package/src/canonical-project.js +25 -9
- package/src/canonical-source.js +6 -1
- package/src/cli.js +5 -2
- package/src/fuzz.js +291 -0
- package/src/git-catalog.js +51 -2
- package/src/index.js +4 -2
- package/src/remote-installer.js +2 -1
- package/src/rule-profile.js +53 -0
- package/src/sync-core.js +34 -6
package/README.md
CHANGED
|
@@ -10,18 +10,41 @@ The npm package contains only the CLI/core runtime. Canonical rules stay in the
|
|
|
10
10
|
npx @specdest/devkit status
|
|
11
11
|
npx @specdest/devkit sync
|
|
12
12
|
npx @specdest/devkit check
|
|
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` is local-only. It executes canonical
|
|
20
|
+
- `check` is local-only. It 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`.
|
|
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.0",
|
|
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,8 @@ 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 { readChecksState, readInstalledState, writeChecksState, writeInstalledState } from './sync-core.js';
|
|
9
10
|
|
|
10
11
|
function execute(command, args, cwd) {
|
|
11
12
|
return new Promise((resolve, reject) => {
|
|
@@ -47,7 +48,9 @@ async function cachedManifest(source, entry, canonicalCheckRoot, checkerRuntimeR
|
|
|
47
48
|
async function canonicalContext(projectRoot, source, options = {}) {
|
|
48
49
|
const catalog = await source.catalog({ refresh: options.refresh ?? false });
|
|
49
50
|
const stack = await detectProjectStack(projectRoot);
|
|
50
|
-
const
|
|
51
|
+
const profile = await readRuleProfile(projectRoot);
|
|
52
|
+
assertKnownRuleOverrides(catalog.entries ?? [], profile);
|
|
53
|
+
const applicable = applicableCatalogEntries(catalog.entries ?? [], stack, profile);
|
|
51
54
|
const canonicalCheck = (catalog.entries ?? []).find((entry) => entry.id === 'canonical-check');
|
|
52
55
|
const checkerRuntime = (catalog.entries ?? []).find((entry) => entry.id === 'checker-runtime');
|
|
53
56
|
let canonicalCheckRoot = null;
|
|
@@ -62,7 +65,7 @@ async function canonicalContext(projectRoot, source, options = {}) {
|
|
|
62
65
|
checkerRuntimeRoot = await source.module(checkerRuntime.id, checkerRuntime.version, { contentHash: checkerRuntime.contentHash });
|
|
63
66
|
}
|
|
64
67
|
}
|
|
65
|
-
return { catalog, stack, applicable, canonicalCheckRoot, checkerRuntimeRoot };
|
|
68
|
+
return { catalog, stack, profile, applicable, canonicalCheckRoot, checkerRuntimeRoot };
|
|
66
69
|
}
|
|
67
70
|
|
|
68
71
|
export async function canonicalStatus(projectRoot, source, options = {}) {
|
|
@@ -89,6 +92,44 @@ export async function canonicalStatus(projectRoot, source, options = {}) {
|
|
|
89
92
|
};
|
|
90
93
|
}
|
|
91
94
|
|
|
95
|
+
async function refreshInstalledRevision(projectRoot, id, revision) {
|
|
96
|
+
const state = await readInstalledState(projectRoot);
|
|
97
|
+
if (!state.installed[id]) throw new Error(`Installed rule missing during provenance refresh: ${id}`);
|
|
98
|
+
state.installed[id] = { ...state.installed[id], revision };
|
|
99
|
+
await writeInstalledState(projectRoot, state);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function cleanupCanonicalInstallState(projectRoot, catalogEntries) {
|
|
103
|
+
const installedState = await readInstalledState(projectRoot);
|
|
104
|
+
const catalogRules = new Set(
|
|
105
|
+
(catalogEntries ?? []).filter((entry) => entry.kind === 'rule').map((entry) => entry.id),
|
|
106
|
+
);
|
|
107
|
+
const requestedStacks = new Set(
|
|
108
|
+
installedState.requested.filter((id) => id.startsWith('stack-')),
|
|
109
|
+
);
|
|
110
|
+
const removed = [];
|
|
111
|
+
for (const id of Object.keys(installedState.installed)) {
|
|
112
|
+
if (catalogRules.has(id) || requestedStacks.has(id)) continue;
|
|
113
|
+
delete installedState.installed[id];
|
|
114
|
+
removed.push(id);
|
|
115
|
+
}
|
|
116
|
+
const nextRequested = installedState.requested.filter(
|
|
117
|
+
(id) => id.startsWith('stack-') && Boolean(installedState.installed[id]),
|
|
118
|
+
);
|
|
119
|
+
const requestedChanged = JSON.stringify(nextRequested) !== JSON.stringify(installedState.requested);
|
|
120
|
+
installedState.requested = nextRequested;
|
|
121
|
+
if (!removed.length && !requestedChanged) return [];
|
|
122
|
+
await writeInstalledState(projectRoot, installedState);
|
|
123
|
+
|
|
124
|
+
const runtimeState = await readChecksState(projectRoot);
|
|
125
|
+
for (const id of removed) {
|
|
126
|
+
delete runtimeState.results[id];
|
|
127
|
+
if (runtimeState.ownership) delete runtimeState.ownership[id];
|
|
128
|
+
}
|
|
129
|
+
await writeChecksState(projectRoot, runtimeState);
|
|
130
|
+
return removed.sort();
|
|
131
|
+
}
|
|
132
|
+
|
|
92
133
|
async function cleanupCanonicalSkillTree(projectRoot, allowedFiles) {
|
|
93
134
|
const root = join(projectRoot, '.agents', 'skills');
|
|
94
135
|
async function walk(directory) {
|
|
@@ -111,7 +152,7 @@ async function cleanupCanonicalSkillTree(projectRoot, allowedFiles) {
|
|
|
111
152
|
|
|
112
153
|
export async function canonicalSync(projectRoot, source) {
|
|
113
154
|
const current = await readInstalledState(projectRoot);
|
|
114
|
-
const { stack, applicable, canonicalCheckRoot, checkerRuntimeRoot } = await canonicalContext(projectRoot, source, { refresh: true, withCheckers: true });
|
|
155
|
+
const { catalog, stack, applicable, canonicalCheckRoot, checkerRuntimeRoot } = await canonicalContext(projectRoot, source, { refresh: true, withCheckers: true });
|
|
115
156
|
const changed = [];
|
|
116
157
|
const allowedSkillFiles = new Set();
|
|
117
158
|
for (const entry of applicable) {
|
|
@@ -124,25 +165,33 @@ export async function canonicalSync(projectRoot, source) {
|
|
|
124
165
|
if (!installed) {
|
|
125
166
|
await installRule({ projectRoot, payloadRoot: source.cachedModulePath(entry.id, entry.version), manifest: prepared.manifest });
|
|
126
167
|
changed.push({ id: entry.id, action: 'installed', version: entry.version });
|
|
127
|
-
} else
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
168
|
+
} else {
|
|
169
|
+
const requiresContentSync =
|
|
170
|
+
installed.version !== entry.version ||
|
|
171
|
+
installed.contentHash !== entry.contentHash ||
|
|
172
|
+
(prepared.checkerPath && installed.check?.command?.[0] !== 'specdest-cache') ||
|
|
173
|
+
await missingProjectScaffold(projectRoot, prepared.manifest.copies);
|
|
174
|
+
if (requiresContentSync) {
|
|
175
|
+
await syncRule({ projectRoot, payloadRoot: source.cachedModulePath(entry.id, entry.version), manifest: prepared.manifest });
|
|
176
|
+
changed.push({ id: entry.id, action: 'updated', version: entry.version });
|
|
177
|
+
} else if (installed.revision !== entry.revision) {
|
|
178
|
+
await refreshInstalledRevision(projectRoot, entry.id, entry.revision);
|
|
179
|
+
changed.push({ id: entry.id, action: 'provenance-refreshed', version: entry.version });
|
|
180
|
+
}
|
|
135
181
|
}
|
|
136
182
|
}
|
|
183
|
+
const removed = await cleanupCanonicalInstallState(projectRoot, catalog.entries ?? []);
|
|
137
184
|
await cleanupCanonicalSkillTree(projectRoot, allowedSkillFiles);
|
|
138
|
-
return { stack, applicable: applicable.length, changed };
|
|
185
|
+
return { stack, applicable: applicable.length, changed, removed };
|
|
139
186
|
}
|
|
140
187
|
|
|
141
|
-
export async function canonicalCheck(projectRoot, source) {
|
|
188
|
+
export async function canonicalCheck(projectRoot, source, options = {}) {
|
|
142
189
|
const current = await readInstalledState(projectRoot);
|
|
143
190
|
const { applicable, canonicalCheckRoot, checkerRuntimeRoot } = await canonicalContext(projectRoot, source, { offline: false, withCheckers: true });
|
|
144
191
|
const byId = new Map(applicable.map((entry) => [entry.id, entry]));
|
|
145
192
|
const results = {};
|
|
193
|
+
const groups = new Map();
|
|
194
|
+
const executor = options.executor ?? execute;
|
|
146
195
|
let exitCode = 0;
|
|
147
196
|
for (const [id, installed] of Object.entries(current.installed).sort(([a], [b]) => a.localeCompare(b))) {
|
|
148
197
|
const entry = byId.get(id);
|
|
@@ -154,16 +203,109 @@ export async function canonicalCheck(projectRoot, source) {
|
|
|
154
203
|
exitCode = 1;
|
|
155
204
|
continue;
|
|
156
205
|
}
|
|
157
|
-
const
|
|
158
|
-
|
|
206
|
+
const key = prepared.checkerKey ?? `path:${prepared.checkerPath}:${JSON.stringify(prepared.checkerArgs ?? [])}`;
|
|
207
|
+
const group = groups.get(key) ?? {
|
|
208
|
+
checkerPath: prepared.checkerPath,
|
|
209
|
+
checkerArgs: prepared.checkerArgs ?? [],
|
|
210
|
+
ids: [],
|
|
211
|
+
};
|
|
212
|
+
group.ids.push(id);
|
|
213
|
+
groups.set(key, group);
|
|
214
|
+
}
|
|
215
|
+
for (const group of groups.values()) {
|
|
216
|
+
const execution = await executor('node', [group.checkerPath, ...group.checkerArgs], projectRoot);
|
|
217
|
+
const result = { status: execution.exitCode === 0 ? 'pass' : 'fail', ...execution };
|
|
218
|
+
for (const id of group.ids) results[id] = result;
|
|
159
219
|
if (execution.exitCode !== 0) exitCode = 1;
|
|
160
220
|
}
|
|
221
|
+
const orderedResults = Object.fromEntries(
|
|
222
|
+
Object.entries(results).sort(([a], [b]) => a.localeCompare(b)),
|
|
223
|
+
);
|
|
161
224
|
await writeChecksState(projectRoot, {
|
|
162
225
|
schemaVersion: 2,
|
|
163
226
|
checkedAt: new Date().toISOString(),
|
|
164
|
-
results: Object.fromEntries(Object.entries(
|
|
227
|
+
results: Object.fromEntries(Object.entries(orderedResults).map(([id, result]) => [id, { status: result.status }])),
|
|
165
228
|
});
|
|
166
|
-
return { exitCode, results };
|
|
229
|
+
return { exitCode, results: orderedResults };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
function rulesFlags(args) {
|
|
234
|
+
const result = { json: false, ids: [], categories: [], failed: false };
|
|
235
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
236
|
+
const arg = args[index];
|
|
237
|
+
if (arg === '--json') result.json = true;
|
|
238
|
+
else if (arg === '--failed') result.failed = true;
|
|
239
|
+
else if (arg === '--id' && args[index + 1]) result.ids.push(args[++index]);
|
|
240
|
+
else if (arg === '--category' && args[index + 1]) result.categories.push(args[++index]);
|
|
241
|
+
else throw new Error(`Unknown option: ${arg}`);
|
|
242
|
+
}
|
|
243
|
+
return result;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function aiMode(entry) {
|
|
247
|
+
if (entry.ai?.load) return entry.ai.load;
|
|
248
|
+
return 'failure-only';
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function ruleSummary(entry) {
|
|
252
|
+
if (entry.summary) return String(entry.summary).trim();
|
|
253
|
+
const content = String(entry.content ?? '').replace(/\r\n?/gu, '\n');
|
|
254
|
+
const intent = content.match(/(?:^|\n)## Intent\s*\n+([^#][\s\S]*?)(?=\n## |$)/u)?.[1]?.trim();
|
|
255
|
+
const source = intent || content
|
|
256
|
+
.split('\n')
|
|
257
|
+
.map((line) => line.trim())
|
|
258
|
+
.find((line) => line && !line.startsWith('#')) || entry.name || entry.id;
|
|
259
|
+
return source
|
|
260
|
+
.replace(/^\*\*Rule:\*\*\s*/u, '')
|
|
261
|
+
.replace(/\s+/gu, ' ')
|
|
262
|
+
.slice(0, 240)
|
|
263
|
+
.trim();
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function aiInstructionText() {
|
|
267
|
+
return [
|
|
268
|
+
'Specdest Devkit governs repository engineering rules.',
|
|
269
|
+
'Do not preload the full rule catalog.',
|
|
270
|
+
'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.',
|
|
271
|
+
'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.',
|
|
272
|
+
].join('\n');
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export async function canonicalRules(projectRoot, source, options = {}) {
|
|
276
|
+
const { stack, profile, applicable } = await canonicalContext(projectRoot, source);
|
|
277
|
+
let selected = applicable;
|
|
278
|
+
let detail = false;
|
|
279
|
+
if (options.ids?.length) {
|
|
280
|
+
const wanted = new Set(options.ids);
|
|
281
|
+
selected = selected.filter((entry) => wanted.has(entry.id));
|
|
282
|
+
detail = true;
|
|
283
|
+
} else if (options.categories?.length) {
|
|
284
|
+
const wanted = new Set(options.categories.map((value) => value.toLowerCase()));
|
|
285
|
+
selected = selected.filter((entry) => wanted.has(String(entry.category ?? '').toLowerCase()));
|
|
286
|
+
} else if (options.failed) {
|
|
287
|
+
const state = await readChecksState(projectRoot);
|
|
288
|
+
const failed = new Set(Object.entries(state.results ?? {}).filter(([, value]) => value.status === 'fail').map(([id]) => id));
|
|
289
|
+
selected = selected.filter((entry) => failed.has(entry.id));
|
|
290
|
+
detail = true;
|
|
291
|
+
} else {
|
|
292
|
+
selected = selected.filter((entry) => aiMode(entry) === 'always');
|
|
293
|
+
}
|
|
294
|
+
return {
|
|
295
|
+
stack,
|
|
296
|
+
profile,
|
|
297
|
+
detail,
|
|
298
|
+
rules: selected.map((entry) => ({
|
|
299
|
+
id: entry.id,
|
|
300
|
+
name: entry.name,
|
|
301
|
+
category: entry.category ?? null,
|
|
302
|
+
enforcement: entry.enforcement ?? 'guidance',
|
|
303
|
+
aiLoad: aiMode(entry),
|
|
304
|
+
summary: ruleSummary(entry),
|
|
305
|
+
composedOf: entry.composedOf ?? [],
|
|
306
|
+
...(detail ? { content: entry.content ?? '' } : {}),
|
|
307
|
+
})),
|
|
308
|
+
};
|
|
167
309
|
}
|
|
168
310
|
|
|
169
311
|
export async function canonicalDoctor(projectRoot, source) {
|
|
@@ -197,6 +339,24 @@ export function createCanonicalCommandHandlers(projectRoot = process.cwd(), opti
|
|
|
197
339
|
for (const [id, check] of Object.entries(result.results)) io.stdout.write(`${check.status.toUpperCase()} ${id}\n`);
|
|
198
340
|
return result.exitCode;
|
|
199
341
|
},
|
|
342
|
+
rules: async (args, io) => {
|
|
343
|
+
const parsed = rulesFlags(args);
|
|
344
|
+
const result = await canonicalRules(projectRoot, source, parsed);
|
|
345
|
+
if (parsed.json) io.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
346
|
+
else {
|
|
347
|
+
for (const rule of result.rules) {
|
|
348
|
+
const body = result.detail ? rule.content.trim() : rule.summary;
|
|
349
|
+
const composition = rule.composedOf.length ? `\nComposed of: ${rule.composedOf.join(', ')}` : '';
|
|
350
|
+
io.stdout.write(`## ${rule.id} — ${rule.name}\n${body}${composition}\n\n`);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return 0;
|
|
354
|
+
},
|
|
355
|
+
'ai-instruction': async (args, io) => {
|
|
356
|
+
if (args.length) { io.stderr.write('Usage: specdest ai-instruction\n'); return 2; }
|
|
357
|
+
io.stdout.write(`${aiInstructionText()}\n`);
|
|
358
|
+
return 0;
|
|
359
|
+
},
|
|
200
360
|
doctor: async (args, io) => {
|
|
201
361
|
if (args.length) { io.stderr.write('Usage: specdest doctor\n'); return 2; }
|
|
202
362
|
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 { ruleApplies } from './rule-profile.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) => ruleApplies(entry, stack, profile))
|
|
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 });
|
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,11 @@ function notApplicableRuleIds(manifest) {
|
|
|
53
67
|
return [...new Set(manifest.notApplicableRuleIds.map(String))].sort();
|
|
54
68
|
}
|
|
55
69
|
|
|
70
|
+
function stringList(value) {
|
|
71
|
+
if (!Array.isArray(value) || value.length === 0) return undefined;
|
|
72
|
+
return [...new Set(value.map(String))].sort();
|
|
73
|
+
}
|
|
74
|
+
|
|
56
75
|
function applicableStacks(manifest) {
|
|
57
76
|
if (manifest.scope !== 'Stack-specific') return undefined;
|
|
58
77
|
if (!Array.isArray(manifest.applicableStacks) || manifest.applicableStacks.length === 0) {
|
|
@@ -65,7 +84,7 @@ export async function buildGitCatalog({ modulesRoot, repositoryRevision = 'worki
|
|
|
65
84
|
const directories = (await readdir(modulesRoot, { withFileTypes: true }))
|
|
66
85
|
.filter((entry) => entry.isDirectory())
|
|
67
86
|
.sort((a, b) => a.name.localeCompare(b.name));
|
|
68
|
-
const
|
|
87
|
+
const modules = [];
|
|
69
88
|
for (const directory of directories) {
|
|
70
89
|
const root = join(modulesRoot, directory.name);
|
|
71
90
|
const files = await moduleFiles(root);
|
|
@@ -73,7 +92,14 @@ export async function buildGitCatalog({ modulesRoot, repositoryRevision = 'worki
|
|
|
73
92
|
if (!manifestFile) throw new Error(`Missing manifest.json: ${directory.name}`);
|
|
74
93
|
const manifest = JSON.parse(manifestFile.content);
|
|
75
94
|
if (manifest.id !== directory.name) throw new Error(`Module id/path mismatch: ${directory.name}`);
|
|
76
|
-
|
|
95
|
+
modules.push({ files, manifest, ownContentHash: sha256(JSON.stringify(files)) });
|
|
96
|
+
}
|
|
97
|
+
const canonicalCheckHash = modules.find(({ manifest }) => manifest.id === 'canonical-check')?.ownContentHash ?? null;
|
|
98
|
+
const entries = [];
|
|
99
|
+
for (const { files, manifest, ownContentHash } of modules) {
|
|
100
|
+
const contentHash = manifest.checker?.path && canonicalCheckHash
|
|
101
|
+
? sha256(JSON.stringify({ ownContentHash, canonicalCheckHash }))
|
|
102
|
+
: ownContentHash;
|
|
77
103
|
const guidance = files.find((file) => /(^|\/)rule\.md$/u.test(file.path) || /(^|\/)SKILL\.md$/u.test(file.path))?.content ?? '';
|
|
78
104
|
const kind = catalogKind(manifest);
|
|
79
105
|
entries.push({
|
|
@@ -82,6 +108,9 @@ export async function buildGitCatalog({ modulesRoot, repositoryRevision = 'worki
|
|
|
82
108
|
version: canonicalVersion(manifest),
|
|
83
109
|
name: title(guidance, manifest.id),
|
|
84
110
|
content: guidance,
|
|
111
|
+
...(kind === 'rule' ? { summary: summary(guidance, manifest.name ?? manifest.id) } : {}),
|
|
112
|
+
...(kind === 'rule' && manifest.category ? { category: String(manifest.category) } : {}),
|
|
113
|
+
...(kind === 'rule' && manifest.scope ? { scope: String(manifest.scope) } : {}),
|
|
85
114
|
group: kind === 'rule' ? 'Rules' : 'Modules',
|
|
86
115
|
order: entries.length + 1,
|
|
87
116
|
source: 'private-devkit-git',
|
|
@@ -90,6 +119,10 @@ export async function buildGitCatalog({ modulesRoot, repositoryRevision = 'worki
|
|
|
90
119
|
...(kind === 'rule' ? { legacyInstalledIds: legacyImplementationIds(manifest) } : {}),
|
|
91
120
|
...(kind === 'rule' ? { enforcement: String(manifest.enforcement ?? 'guidance') } : {}),
|
|
92
121
|
...(kind === 'rule' && applicableStacks(manifest) ? { applicableStacks: applicableStacks(manifest) } : {}),
|
|
122
|
+
...(kind === 'rule' && stringList(manifest.requiredCapabilities) ? { requiredCapabilities: stringList(manifest.requiredCapabilities) } : {}),
|
|
123
|
+
...(kind === 'rule' && manifest.ai ? { ai: manifest.ai } : {}),
|
|
124
|
+
...(kind === 'rule' && manifest.verification ? { verification: manifest.verification } : {}),
|
|
125
|
+
...(kind === 'rule' && stringList(manifest.composedOf) ? { composedOf: stringList(manifest.composedOf) } : {}),
|
|
93
126
|
...(kind === 'module' && notApplicableRuleIds(manifest)
|
|
94
127
|
? { notApplicableRuleIds: notApplicableRuleIds(manifest) }
|
|
95
128
|
: {}),
|
|
@@ -100,6 +133,22 @@ export async function buildGitCatalog({ modulesRoot, repositoryRevision = 'worki
|
|
|
100
133
|
for (const ruleId of entry.notApplicableRuleIds ?? []) {
|
|
101
134
|
if (!ruleIds.has(ruleId)) throw new Error(`Unknown not-applicable rule: ${entry.id}:${ruleId}`);
|
|
102
135
|
}
|
|
136
|
+
for (const childId of entry.composedOf ?? []) {
|
|
137
|
+
if (!ruleIds.has(childId)) throw new Error(`Unknown composed rule: ${entry.id}:${childId}`);
|
|
138
|
+
if (childId === entry.id) throw new Error(`Rule cannot compose itself: ${entry.id}`);
|
|
139
|
+
}
|
|
103
140
|
}
|
|
141
|
+
const composition = new Map(entries.filter((entry) => entry.kind === 'rule').map((entry) => [entry.id, entry.composedOf ?? []]));
|
|
142
|
+
const visiting = new Set();
|
|
143
|
+
const visited = new Set();
|
|
144
|
+
const visit = (id) => {
|
|
145
|
+
if (visiting.has(id)) throw new Error(`Rule composition cycle: ${id}`);
|
|
146
|
+
if (visited.has(id)) return;
|
|
147
|
+
visiting.add(id);
|
|
148
|
+
for (const childId of composition.get(id) ?? []) visit(childId);
|
|
149
|
+
visiting.delete(id);
|
|
150
|
+
visited.add(id);
|
|
151
|
+
};
|
|
152
|
+
for (const id of composition.keys()) visit(id);
|
|
104
153
|
return { schemaVersion: 1, package: { name: '@specdest/devkit', version: repositoryRevision }, entries };
|
|
105
154
|
}
|
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 Run installed rule checks from the local cache\n doctor Diagnose project/cache setup\n`;
|
|
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 Run installed rule checks from the local cache\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;
|
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,53 @@
|
|
|
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({ schemaVersion: 1, capabilities: [], include: [], exclude: [] });
|
|
6
|
+
|
|
7
|
+
function uniqueStrings(values, label) {
|
|
8
|
+
if (!Array.isArray(values ?? [])) throw new Error(`Invalid ${label}`);
|
|
9
|
+
return [...new Set((values ?? []).map(String).map((value) => value.trim()).filter(Boolean))].sort();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function validateRuleProfile(profile) {
|
|
13
|
+
if (!profile || typeof profile !== 'object' || Array.isArray(profile) || profile.schemaVersion !== 1) {
|
|
14
|
+
throw new Error('Invalid .specdest/rules.json profile');
|
|
15
|
+
}
|
|
16
|
+
const capabilities = uniqueStrings(profile.capabilities, 'rule profile capabilities');
|
|
17
|
+
const include = uniqueStrings(profile.include, 'rule profile include');
|
|
18
|
+
if (!Array.isArray(profile.exclude ?? [])) throw new Error('Invalid rule profile exclude');
|
|
19
|
+
const exclude = (profile.exclude ?? []).map((item) => {
|
|
20
|
+
if (!item || typeof item !== 'object' || !String(item.id ?? '').trim() || !String(item.reason ?? '').trim()) {
|
|
21
|
+
throw new Error('Rule exclusions require both id and non-empty reason');
|
|
22
|
+
}
|
|
23
|
+
return { id: String(item.id).trim(), reason: String(item.reason).trim() };
|
|
24
|
+
}).sort((a, b) => a.id.localeCompare(b.id));
|
|
25
|
+
return { schemaVersion: 1, capabilities, include, exclude };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function readRuleProfile(projectRoot) {
|
|
29
|
+
try {
|
|
30
|
+
const raw = JSON.parse(await readFile(join(projectRoot, RULE_PROFILE_RELATIVE_PATH), 'utf8'));
|
|
31
|
+
return validateRuleProfile(raw);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if (error?.code === 'ENOENT') return { ...EMPTY_RULE_PROFILE, capabilities: [], include: [], exclude: [] };
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function ruleApplies(entry, stack, profile = EMPTY_RULE_PROFILE) {
|
|
39
|
+
const included = new Set(profile.include ?? []);
|
|
40
|
+
const excluded = new Set((profile.exclude ?? []).map((item) => item.id));
|
|
41
|
+
if (excluded.has(entry.id)) return false;
|
|
42
|
+
if (included.has(entry.id)) return true;
|
|
43
|
+
if (entry.applicableStacks?.length && (!stack || !entry.applicableStacks.includes(stack))) return false;
|
|
44
|
+
const capabilities = new Set(profile.capabilities ?? []);
|
|
45
|
+
if (entry.requiredCapabilities?.some((capability) => !capabilities.has(capability))) return false;
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function assertKnownRuleOverrides(entries, profile) {
|
|
50
|
+
const ids = new Set(entries.filter((entry) => entry.kind === 'rule').map((entry) => entry.id));
|
|
51
|
+
for (const id of profile.include ?? []) if (!ids.has(id)) throw new Error(`Unknown included rule: ${id}`);
|
|
52
|
+
for (const item of profile.exclude ?? []) if (!ids.has(item.id)) throw new Error(`Unknown excluded rule: ${item.id}`);
|
|
53
|
+
}
|
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) {
|