@specdest/devkit 0.4.5 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +34 -4
  2. package/dist/npm/canonical-project-operations.d.ts +5 -0
  3. package/dist/npm/canonical-project-operations.js +5 -0
  4. package/dist/npm/canonical-project.d.ts +10 -0
  5. package/dist/npm/canonical-project.js +109 -0
  6. package/dist/npm/canonical-source.d.ts +14 -0
  7. package/dist/npm/canonical-source.js +216 -0
  8. package/dist/npm/catalog-snapshot.d.ts +47 -0
  9. package/dist/npm/catalog-snapshot.js +28 -0
  10. package/dist/npm/cli.d.ts +2 -0
  11. package/dist/npm/cli.js +15 -0
  12. package/dist/npm/commands.d.ts +9 -0
  13. package/dist/npm/commands.js +157 -0
  14. package/dist/npm/flow.d.ts +48 -0
  15. package/dist/npm/flow.js +396 -0
  16. package/dist/npm/fuzz.d.ts +138 -0
  17. package/dist/npm/fuzz.js +327 -0
  18. package/dist/npm/git-catalog.d.ts +39 -0
  19. package/dist/npm/git-catalog.js +190 -0
  20. package/dist/npm/index.d.ts +5 -0
  21. package/dist/npm/index.js +22 -0
  22. package/dist/npm/installer-primitives.d.ts +3 -0
  23. package/dist/npm/installer-primitives.js +50 -0
  24. package/dist/npm/predefined-packages/abac.d.ts +2 -0
  25. package/dist/npm/predefined-packages/abac.js +22 -0
  26. package/dist/npm/predefined-packages/auth.d.ts +2 -0
  27. package/dist/npm/predefined-packages/auth.js +21 -0
  28. package/dist/npm/predefined-packages/convex.d.ts +2 -0
  29. package/dist/npm/predefined-packages/convex.js +53 -0
  30. package/dist/npm/predefined-packages/expo.d.ts +2 -0
  31. package/dist/npm/predefined-packages/expo.js +84 -0
  32. package/dist/npm/predefined-packages/firebase-hosting.d.ts +2 -0
  33. package/dist/npm/predefined-packages/firebase-hosting.js +24 -0
  34. package/dist/npm/predefined-packages/health.d.ts +10 -0
  35. package/dist/npm/predefined-packages/health.js +52 -0
  36. package/dist/npm/predefined-packages/husky.d.ts +2 -0
  37. package/dist/npm/predefined-packages/husky.js +57 -0
  38. package/dist/npm/predefined-packages/index.d.ts +11 -0
  39. package/dist/npm/predefined-packages/index.js +56 -0
  40. package/dist/npm/predefined-packages/install.d.ts +19 -0
  41. package/dist/npm/predefined-packages/install.js +85 -0
  42. package/dist/npm/predefined-packages/local-logging.d.ts +2 -0
  43. package/dist/npm/predefined-packages/local-logging.js +17 -0
  44. package/dist/npm/predefined-packages/logging.d.ts +2 -0
  45. package/dist/npm/predefined-packages/logging.js +21 -0
  46. package/dist/npm/predefined-packages/multi-tenancy.d.ts +2 -0
  47. package/dist/npm/predefined-packages/multi-tenancy.js +21 -0
  48. package/dist/npm/predefined-packages/nps.d.ts +2 -0
  49. package/dist/npm/predefined-packages/nps.js +32 -0
  50. package/dist/npm/predefined-packages/oxfmt.d.ts +2 -0
  51. package/dist/npm/predefined-packages/oxfmt.js +22 -0
  52. package/dist/npm/predefined-packages/oxlint.d.ts +2 -0
  53. package/dist/npm/predefined-packages/oxlint.js +35 -0
  54. package/dist/npm/predefined-packages/package-json.d.ts +3 -0
  55. package/dist/npm/predefined-packages/package-json.js +61 -0
  56. package/dist/npm/predefined-packages/payments.d.ts +2 -0
  57. package/dist/npm/predefined-packages/payments.js +31 -0
  58. package/dist/npm/predefined-packages/playwright.d.ts +2 -0
  59. package/dist/npm/predefined-packages/playwright.js +35 -0
  60. package/dist/npm/predefined-packages/project-signals.d.ts +4 -0
  61. package/dist/npm/predefined-packages/project-signals.js +39 -0
  62. package/dist/npm/predefined-packages/registry.d.ts +3 -0
  63. package/dist/npm/predefined-packages/registry.js +63 -0
  64. package/dist/npm/predefined-packages/resolver.d.ts +8 -0
  65. package/dist/npm/predefined-packages/resolver.js +35 -0
  66. package/dist/npm/predefined-packages/sentry.d.ts +2 -0
  67. package/dist/npm/predefined-packages/sentry.js +29 -0
  68. package/dist/npm/predefined-packages/shadcn.d.ts +2 -0
  69. package/dist/npm/predefined-packages/shadcn.js +23 -0
  70. package/dist/npm/predefined-packages/storybook.d.ts +2 -0
  71. package/dist/npm/predefined-packages/storybook.js +25 -0
  72. package/dist/npm/predefined-packages/stryker.d.ts +2 -0
  73. package/dist/npm/predefined-packages/stryker.js +48 -0
  74. package/dist/npm/predefined-packages/supabase.d.ts +2 -0
  75. package/dist/npm/predefined-packages/supabase.js +84 -0
  76. package/dist/npm/predefined-packages/tailwind.d.ts +2 -0
  77. package/dist/npm/predefined-packages/tailwind.js +18 -0
  78. package/dist/npm/predefined-packages/tanstack-form.d.ts +2 -0
  79. package/dist/npm/predefined-packages/tanstack-form.js +19 -0
  80. package/dist/npm/predefined-packages/tanstack-query.d.ts +2 -0
  81. package/dist/npm/predefined-packages/tanstack-query.js +15 -0
  82. package/dist/npm/predefined-packages/tanstack-router.d.ts +2 -0
  83. package/dist/npm/predefined-packages/tanstack-router.js +18 -0
  84. package/dist/npm/predefined-packages/types.d.ts +31 -0
  85. package/dist/npm/predefined-packages/types.js +1 -0
  86. package/dist/npm/predefined-packages/vite.d.ts +2 -0
  87. package/dist/npm/predefined-packages/vite.js +123 -0
  88. package/dist/npm/predefined-packages/vitest.d.ts +2 -0
  89. package/dist/npm/predefined-packages/vitest.js +20 -0
  90. package/dist/npm/predefined-packages/zod.d.ts +2 -0
  91. package/dist/npm/predefined-packages/zod.js +18 -0
  92. package/dist/npm/project-check.d.ts +6 -0
  93. package/dist/npm/project-check.js +87 -0
  94. package/dist/npm/project-context.d.ts +42 -0
  95. package/dist/npm/project-context.js +192 -0
  96. package/dist/npm/project-rules.d.ts +22 -0
  97. package/dist/npm/project-rules.js +66 -0
  98. package/dist/npm/project-runtime.d.ts +18 -0
  99. package/dist/npm/project-runtime.js +27 -0
  100. package/dist/npm/project-status.d.ts +32 -0
  101. package/dist/npm/project-status.js +56 -0
  102. package/dist/npm/project-sync.d.ts +7 -0
  103. package/dist/npm/project-sync.js +135 -0
  104. package/dist/npm/remote-installer.d.ts +4 -0
  105. package/dist/npm/remote-installer.js +312 -0
  106. package/dist/npm/state.d.ts +14 -0
  107. package/dist/npm/state.js +182 -0
  108. package/package.json +10 -7
  109. package/src/canonical-project-operations.js +0 -433
  110. package/src/canonical-project.js +0 -136
  111. package/src/canonical-source.js +0 -250
  112. package/src/catalog-snapshot.js +0 -39
  113. package/src/catalog.js +0 -117
  114. package/src/cli.js +0 -14
  115. package/src/fuzz.js +0 -291
  116. package/src/git-catalog.js +0 -177
  117. package/src/index.js +0 -36
  118. package/src/installer-primitives.js +0 -198
  119. package/src/project-operations.js +0 -189
  120. package/src/project-targeting.js +0 -48
  121. package/src/remote-installer.js +0 -479
  122. package/src/rule-profile.js +0 -61
  123. package/src/setup-requirements.js +0 -82
  124. package/src/shared-file.js +0 -131
  125. package/src/sync-core.js +0 -390
package/README.md CHANGED
@@ -2,29 +2,50 @@
2
2
 
3
3
  `@specdest/devkit` is the canonical Devkit CLI for Specdest repositories.
4
4
 
5
+ The CLI/core source is strict TypeScript. Development uses Node 24 directly; npm packaging uses plain `tsc` emit because Node does not strip TypeScript inside `node_modules`. No bundler or alternate runtime is used.
6
+
5
7
  The npm package contains only the CLI/core runtime. Canonical rules stay in the private Devkit GitHub repository and are fetched with normal Git/SSH transport into a local machine cache when needed. Rule changes therefore do not require an npm release.
6
8
 
9
+ The root package API is intentionally small: `runCli`, `COMMAND_NAMES`, `createCanonicalSource`, `createFlowCommandHandler`, and `createFuzzCommandHandler`. Installer, state, sync, and canonical orchestration modules are internal implementation details.
10
+
11
+ `modules/**` is the canonical rule/module source. `catalog/**` is compatibility/test fixture data only; production CLI and release catalog generation do not read it.
12
+
7
13
  ## Commands
8
14
 
9
15
  ```bash
10
16
  npx @specdest/devkit status
17
+ npx @specdest/devkit add vite
11
18
  npx @specdest/devkit sync
12
19
  npx @specdest/devkit check [--refresh]
13
20
  npx @specdest/devkit check --staged
14
21
  npx @specdest/devkit check --files src/path/file.ts
15
22
  npx @specdest/devkit rules
23
+ npx @specdest/devkit ai-instruction
16
24
  npx @specdest/devkit doctor
17
25
  npx @specdest/devkit fuzz
26
+ npx @specdest/devkit flow status
27
+ npx @specdest/devkit flow start --mode feature --goal "Add password reset" --task auth-reset
28
+ npx @specdest/devkit flow checkpoint --phase implement
29
+ npx @specdest/devkit flow verify
30
+ npx @specdest/devkit flow complete
18
31
  ```
19
32
 
20
- - `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.
33
+ - `status` reads the cached canonical catalog and reports applicable/current/missing/outdated rules plus registered predefined packages. Use `--refresh` to refresh the catalog from GitHub and `--json` for machine-readable output.
34
+ - `add <package>` applies or adopts a predefined package recipe. Package recipes use only three relationship primitives: `requires`, `conflicts`, and environment-selected `variants`. `requires` is evaluated against packages registered in Devkit state; conflicts and variant selection also consider packages physically detected in the project. Status/doctor report stale package state, while sync/check/rules refuse to run against invalid package metadata. The supported foundational packages are `vite`, `expo`, `supabase`, and `convex`. Additional predefined packages are `auth`, `multi-tenancy`, `abac`, `sentry`, `logging`, `payments`, `shadcn`, `tanstack-router`, `tanstack-query`, `tanstack-form`, `storybook`, `playwright`, `vitest`, `local-logging`, `firebase-hosting`, `zod`, `tailwind`, `husky`, `nps`, `oxlint`, `oxfmt`, and `stryker`. Create-or-adopt recipes include the foundations (`vite`, `expo`, `supabase`, `convex`) and deterministic self-contained tooling (`zod`, `vitest`, `oxlint`, `oxfmt`, `husky`, `nps`, `tanstack-form`, `playwright`, `stryker`). They create minimal local dependencies/configuration when absent, then run `pnpm install`; when an integration already exists they adopt it without rewriting project-owned application files. Runtime-wired or product-specific recipes remain adoption-only until Devkit has a deterministic, product-neutral installation contract. Recipes record the recipe version separately from any detected dependency version in `.spd/installed.json`; Devkit does not invent product-specific auth, tenancy, authorization, logging, or payment architecture. Generated/adopted application code remains project-owned. Package lifecycle is deliberately fire-and-forget: there is no package `remove` or `upgrade` command. Developers remove packages manually; to update a recipe, re-run `add <package>`. Re-adding applies only the current recipe and does not remove files/settings that existed only in an older recipe. See [`docs/package-model.md`](docs/package-model.md).
21
35
  - `sync` refreshes the canonical catalog, downloads only missing rule-cache entries, installs missing applicable rules, and updates outdated ones.
22
- - `check` executes each distinct canonical checker implementation once from the local Devkit cache and projects that result onto every rule backed by that checker. Use `--refresh` to refresh the canonical catalog/checker cache first without reconciling project files. `--staged` resolves target paths/content from the Git index; `--files` supplies explicit project-relative paths. Repository-scoped checkers still run globally. Targeted checks are ephemeral and do not update `.specdest/state.json`; only a full check records canonical project status.
36
+ - `check` executes each distinct canonical checker implementation once from the local Devkit cache and projects that result onto every rule backed by that checker. Use `--refresh` to refresh the canonical catalog/checker cache first without reconciling project files. `--staged` resolves target paths/content from the Git index; `--files` supplies explicit project-relative paths. Repository-scoped checkers still run globally. Targeted checks are ephemeral and do not update `.spd/state.json`; only a full check records canonical project status.
23
37
  - `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"`.
24
38
  - `doctor` reports project-stack/cache setup problems.
25
39
  - `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.
40
+ - `flow` manages local, resumable development state under `.spd/`. Canonical workflows are fixed: Feature/Fix use `plan → implement → verify → complete`; Inspect uses `plan → complete`. Use `--task <id>` when multiple tasks exist and `--context-file flow-notes/<task>.md` only when rich working context is needed. `flow verify` runs the repository's existing `.husky/pre-push` gate when present, otherwise its package `check` script; completion requires a successful, still-current verification. Runtime state is local-only and removed on completion.
41
+
42
+ ## AI usage
43
+
44
+ `npx @specdest/devkit ai-instruction` prints the minimal, tool-agnostic bootstrap for coding agents. Agents should inspect DevKit Flow state before repository work, while semantic task classification and worktree choice remain agent-policy decisions. DevKit Flow owns persisted task state, phase transitions, verification, and completion; DevKit rules/checks own deterministic repository enforcement. Agent-specific policy such as ChatGPT's `@specdest-development` skill belongs outside DevKit rather than being duplicated in the CLI.
26
45
 
27
- 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.
46
+ The CLI resolves a project stack from supported Expo/Vite + Convex/Supabase package dependencies when possible; otherwise it uses the single committed requested `stack-*` root in `.spd/installed.json`. Explicit predefined-package registrations are committed as requested `kind: "package"` entries with separate `recipeVersion` and `detectedVersion` fields, and are preserved by canonical rule sync. Foundational adapters such as Vite use the same recipe mechanism as feature packages; `role` metadata distinguishes frontend/backend/foundation intent without a separate installer architecture. Canonical rules may declare `requiredPackages` (for example `vite` or `supabase`) instead of enumerating every compatible stack; legacy stack applicability remains supported during migration. Optional `.spd/rules.json` adds the project type/capabilities plus explicit rule includes/exclusions; every exclusion requires a reason. `.spd/installed.json` and `.spd/state.json` remain the committed project status used by the Base rules matrix.
47
+
48
+ `.spd/` is the canonical local Specdest metadata namespace. Normal DevKit usage automatically renames a legacy `.specdest/` directory to `.spd/` when no canonical directory exists. If both directories exist, `.spd/` wins only when every legacy file has an identical canonical counterpart; legacy-only or differing files fail with an explicit metadata namespace conflict instead of being overwritten. During sync, legacy managed-markdown ownership records are normalized to the current section format only after their recorded hash still matches the project content, preserving conflict protection while allowing older adopted repositories to migrate.
28
49
 
29
50
  See [`docs/operations.md`](docs/operations.md) for cache, dashboard, CI, and release behavior.
30
51
 
@@ -34,7 +55,7 @@ See [`docs/operations.md`](docs/operations.md) for cache, dashboard, CI, and rel
34
55
 
35
56
  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.
36
57
 
37
- If default discovery is not appropriate, add `.specdest/fuzz.json`:
58
+ If default discovery is not appropriate, add `.spd/fuzz.json`:
38
59
 
39
60
  ```json
40
61
  {
@@ -50,3 +71,12 @@ Current module loading supports Node 24 TypeScript, extensionless relative impor
50
71
  ## Canonical cache runtime
51
72
 
52
73
  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.
74
+ Project state has one runtime owner: `src/state.ts` reads, validates, formats, and atomically writes `.spd/installed.json` and `.spd/state.json`. Sync/install/check code must use that module rather than implementing state IO independently.
75
+
76
+ Project applicability has one runtime owner: `src/project-context.ts` detects the stack, reads `.spd/rules.json`, resolves project type/capabilities, validates overrides, and selects applicable canonical rules.
77
+
78
+ Project operations are split by behavior: `project-status.ts`, `project-sync.ts`, `project-check.ts`, and `project-rules.ts`; `commands.ts` is only the CLI adapter, while `canonical-project-operations.ts` remains a compatibility re-export.
79
+
80
+ The canonical installer intentionally supports only managed file copies, create-once scaffold files, and managed Markdown sections. Canonical manifests must not rely on generic JSON/YAML/env mutation, directory-copy, delete, or lifecycle-script operations.
81
+
82
+ The legacy generic sync planner (`sync-core.js`), shared-file mutation runtime, and setup-requirement evaluator have been removed from the shipped CLI. Compatibility catalog validation for those historical manifest shapes lives only under `test/support`.
@@ -0,0 +1,5 @@
1
+ export { createCanonicalCommandHandlers } from './commands.ts';
2
+ export { canonicalCheck } from './project-check.ts';
3
+ export { aiInstructionText, canonicalRules } from './project-rules.ts';
4
+ export { canonicalDoctor, canonicalStatus } from './project-status.ts';
5
+ export { canonicalSync } from './project-sync.ts';
@@ -0,0 +1,5 @@
1
+ export { createCanonicalCommandHandlers } from "./commands.js";
2
+ export { canonicalCheck } from "./project-check.js";
3
+ export { aiInstructionText, canonicalRules } from "./project-rules.js";
4
+ export { canonicalDoctor, canonicalStatus } from "./project-status.js";
5
+ export { canonicalSync } from "./project-sync.js";
@@ -0,0 +1,10 @@
1
+ export declare function prepareCachedManifest(entry: any, ruleRoot: any, canonicalCheckRoot: any, checkerRuntimeRoot?: any): Promise<{
2
+ manifest: any;
3
+ checkerPath: string | null;
4
+ checkerArgs: any;
5
+ checkerKey: string | null;
6
+ targeting: {
7
+ scope: any;
8
+ };
9
+ execution: any;
10
+ }>;
@@ -0,0 +1,109 @@
1
+ import { cp, mkdir, readFile, rm } from 'node:fs/promises';
2
+ import { basename, dirname, join } from 'node:path';
3
+ function isSkillTarget(copy) {
4
+ return String(copy?.target ?? copy?.path ?? '').startsWith('.agents/skills/');
5
+ }
6
+ function isProjectScaffold(copy) {
7
+ return copy?.mode === 'scaffold' || copy?.mode === 'create-only';
8
+ }
9
+ function keepProjectCopy(copy) {
10
+ return !isSkillTarget(copy) || isProjectScaffold(copy);
11
+ }
12
+ async function materializeCopies(manifest, sourceRoot, runtimeRoot) {
13
+ for (const copy of manifest?.copies ?? []) {
14
+ if (!isSkillTarget(copy) || isProjectScaffold(copy))
15
+ continue;
16
+ const source = join(sourceRoot, String(copy.source ?? ''));
17
+ const target = join(runtimeRoot, String(copy.target ?? copy.path ?? ''));
18
+ await mkdir(dirname(target), { recursive: true });
19
+ await cp(source, target, { recursive: copy.type === 'directory' || copy.directory === true, force: true });
20
+ }
21
+ }
22
+ async function readManifest(root) {
23
+ return JSON.parse(await readFile(join(root, 'manifest.json'), 'utf8'));
24
+ }
25
+ async function cacheProjectCopies(copies, sourceRoot, ruleRoot, label) {
26
+ const result = [];
27
+ for (const copy of copies.filter(keepProjectCopy)) {
28
+ if (sourceRoot === ruleRoot) {
29
+ result.push(copy);
30
+ continue;
31
+ }
32
+ const source = String(copy.source ?? '');
33
+ const cachedSource = join('.project-scaffolds', label, source);
34
+ const target = join(ruleRoot, cachedSource);
35
+ await mkdir(dirname(target), { recursive: true });
36
+ await cp(join(sourceRoot, source), target, {
37
+ recursive: copy.type === 'directory' || copy.directory === true,
38
+ force: true,
39
+ });
40
+ result.push({ ...copy, source: cachedSource });
41
+ }
42
+ return result;
43
+ }
44
+ function checkerPolicy(manifest) {
45
+ const scope = manifest?.targeting?.scope ?? 'repository';
46
+ if (!['file', 'related', 'repository'].includes(scope))
47
+ throw new Error(`Invalid checker targeting scope: ${scope}`);
48
+ const execution = manifest?.execution ?? 'automatic';
49
+ if (!['automatic', 'manual'].includes(execution))
50
+ throw new Error(`Invalid checker execution class: ${execution}`);
51
+ return { targeting: { scope }, execution };
52
+ }
53
+ function runtimeChecker(manifest, runtimeRoot) {
54
+ if (manifest?.check?.command?.[0] !== 'node')
55
+ return null;
56
+ const target = String(manifest.check.command[1] ?? '');
57
+ if (!target.startsWith('.agents/skills/'))
58
+ return null;
59
+ return {
60
+ path: join(runtimeRoot, target),
61
+ args: manifest.check.command.slice(2).map(String),
62
+ };
63
+ }
64
+ export async function prepareCachedManifest(entry, ruleRoot, canonicalCheckRoot, checkerRuntimeRoot = null) {
65
+ const raw = await readManifest(ruleRoot);
66
+ const checkerKey = raw.checker?.path
67
+ ? `canonical:${String(raw.checker.path)}`
68
+ : raw.check?.command
69
+ ? `command:${JSON.stringify(raw.check.command)}`
70
+ : null;
71
+ const runtimeRoot = join(ruleRoot, '.runtime');
72
+ await rm(runtimeRoot, { recursive: true, force: true });
73
+ await mkdir(runtimeRoot, { recursive: true });
74
+ if (checkerRuntimeRoot) {
75
+ await materializeCopies(await readManifest(checkerRuntimeRoot), checkerRuntimeRoot, runtimeRoot);
76
+ }
77
+ await materializeCopies(raw, ruleRoot, runtimeRoot);
78
+ const copies = await cacheProjectCopies(raw.copies ?? [], ruleRoot, ruleRoot, entry.id);
79
+ let checker = runtimeChecker(raw, runtimeRoot);
80
+ let { targeting, execution } = checkerPolicy(raw);
81
+ if (!checker && raw.checker?.path && canonicalCheckRoot) {
82
+ const relative = String(raw.checker.path).replace(/^canonical-check\//u, '');
83
+ const implementationRoot = dirname(join(canonicalCheckRoot, relative));
84
+ const implementationManifest = await readManifest(implementationRoot);
85
+ ({ targeting, execution } = checkerPolicy(implementationManifest));
86
+ await materializeCopies(implementationManifest, implementationRoot, runtimeRoot);
87
+ copies.push(...await cacheProjectCopies(implementationManifest.copies ?? [], implementationRoot, ruleRoot, basename(implementationRoot)));
88
+ checker = runtimeChecker(implementationManifest, runtimeRoot);
89
+ }
90
+ const markdownSections = (raw.markdownSections ?? []).filter((section) => !String(section?.body ?? section?.content ?? '').includes('.agents/skills/'));
91
+ const manifest = {
92
+ ...raw,
93
+ kind: raw.kind ?? entry.kind ?? 'rule',
94
+ version: entry.version ?? raw.version,
95
+ ...(entry.contentHash ? { contentHash: entry.contentHash } : {}),
96
+ ...(entry.revision ? { revision: entry.revision } : {}),
97
+ copies: [...new Map(copies.map((copy) => [String(copy.target ?? copy.path ?? copy.source), copy])).values()],
98
+ markdownSections,
99
+ ...(checker ? { check: { command: ['specdest-cache', entry.id] } } : {}),
100
+ };
101
+ return {
102
+ manifest,
103
+ checkerPath: checker?.path ?? null,
104
+ checkerArgs: checker?.args ?? [],
105
+ checkerKey,
106
+ targeting,
107
+ execution,
108
+ };
109
+ }
@@ -0,0 +1,14 @@
1
+ export declare function createCanonicalSource(options?: any): {
2
+ cacheRoot: any;
3
+ cachedModulePath(id: any, version: any): string;
4
+ hasModule(id: any, version: any, contentHash?: any): Promise<boolean>;
5
+ catalog({ refresh }?: any): Promise<any>;
6
+ module(id: any, version: any, { refresh, contentHash }?: any): Promise<string>;
7
+ };
8
+ export declare function fetchGitHubCatalog(options?: any): Promise<any>;
9
+ export declare function fetchGitHubModule(id: any, options?: any): Promise<{
10
+ files: {
11
+ path: string;
12
+ content: string;
13
+ }[];
14
+ }>;
@@ -0,0 +1,216 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
5
+ const DEFAULT_REPOSITORY = 'specdest-org/devkit';
6
+ const DEFAULT_REF = 'main';
7
+ async function exists(path) {
8
+ try {
9
+ await stat(path);
10
+ return true;
11
+ }
12
+ catch (error) {
13
+ if (error?.code === 'ENOENT')
14
+ return false;
15
+ throw error;
16
+ }
17
+ }
18
+ function defaultCacheRoot(env = process.env) {
19
+ return join(env.XDG_CACHE_HOME?.trim() || join(homedir(), '.cache'), 'specdest', 'devkit');
20
+ }
21
+ function repositoryUrl(options = {}) {
22
+ if (options.repositoryUrl)
23
+ return String(options.repositoryUrl);
24
+ const repository = String(options.repository ?? DEFAULT_REPOSITORY);
25
+ if (repository.startsWith('/') || repository.startsWith('.') || repository.includes('://') || repository.startsWith('git@')) {
26
+ return repository;
27
+ }
28
+ return `git@github.com:${repository}.git`;
29
+ }
30
+ function run(command, args, options = {}) {
31
+ return new Promise((resolve, reject) => {
32
+ const child = spawn(command, args, { cwd: options.cwd, stdio: ['ignore', 'pipe', 'pipe'] });
33
+ let stdout = '';
34
+ let stderr = '';
35
+ child.stdout.setEncoding('utf8');
36
+ child.stderr.setEncoding('utf8');
37
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
38
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
39
+ child.on('error', reject);
40
+ child.on('close', (code) => code === 0 ? resolve(stdout) : reject(new Error(`${command} exited ${code}: ${stderr.trim()}`)));
41
+ });
42
+ }
43
+ async function ensureGitRepository(cacheRoot, options = {}) {
44
+ const gitDir = join(cacheRoot, 'source.git');
45
+ const url = repositoryUrl(options);
46
+ const ref = String(options.ref ?? DEFAULT_REF);
47
+ if (!(await exists(join(gitDir, 'HEAD')))) {
48
+ await mkdir(cacheRoot, { recursive: true });
49
+ await run('git', ['clone', '--bare', '--single-branch', '--branch', ref, url, gitDir]);
50
+ }
51
+ else {
52
+ const configured = (await run('git', ['--git-dir', gitDir, 'remote', 'get-url', 'origin'])).trim();
53
+ if (configured !== url)
54
+ throw new Error(`Canonical Devkit cache remote mismatch: ${configured}`);
55
+ }
56
+ return gitDir;
57
+ }
58
+ async function fetchGitRevision(cacheRoot, options = {}) {
59
+ const gitDir = await ensureGitRepository(cacheRoot, options);
60
+ const ref = String(options.ref ?? DEFAULT_REF);
61
+ await run('git', ['--git-dir', gitDir, 'fetch', '--prune', 'origin', ref]);
62
+ const revision = (await run('git', ['--git-dir', gitDir, 'rev-parse', 'FETCH_HEAD'])).trim();
63
+ return { gitDir, revision };
64
+ }
65
+ async function readGitFile(gitDir, revision, path) {
66
+ return await run('git', ['--git-dir', gitDir, 'show', `${revision}:${path}`]);
67
+ }
68
+ async function readGitModule(gitDir, revision, id) {
69
+ const prefix = `modules/${id}/`;
70
+ const listed = await run('git', ['--git-dir', gitDir, 'ls-tree', '-r', '--name-only', revision, '--', `modules/${id}`]);
71
+ const paths = listed.split('\n').map((value) => value.trim()).filter((value) => value.startsWith(prefix));
72
+ if (!paths.length)
73
+ throw new Error(`Canonical module directory not found: ${id}`);
74
+ const files = [];
75
+ for (const path of paths.sort()) {
76
+ files.push({ path: path.slice(prefix.length), content: await readGitFile(gitDir, revision, path) });
77
+ }
78
+ return { files };
79
+ }
80
+ async function writePayload(root, files) {
81
+ for (const file of files) {
82
+ const target = join(root, file.path);
83
+ await mkdir(dirname(target), { recursive: true });
84
+ await writeFile(target, file.content, 'utf8');
85
+ }
86
+ }
87
+ async function readMarker(path) {
88
+ try {
89
+ return JSON.parse(await readFile(path, 'utf8'));
90
+ }
91
+ catch (error) {
92
+ if (error?.code === 'ENOENT' || error instanceof SyntaxError)
93
+ return null;
94
+ throw error;
95
+ }
96
+ }
97
+ function markerMatches(marker, id, version, contentHash) {
98
+ return Boolean(marker && marker.id === id && marker.version === version && (!contentHash || marker.contentHash === contentHash));
99
+ }
100
+ export function createCanonicalSource(options = {}) {
101
+ const cacheRoot = options.cacheRoot ?? defaultCacheRoot(options.env);
102
+ const catalogPath = join(cacheRoot, 'catalog.json');
103
+ const catalogMetaPath = join(cacheRoot, 'catalog-meta.json');
104
+ const customFetch = Boolean(options.fetchCatalog || options.fetchModule);
105
+ let activeRevision = null;
106
+ let activeGitDir = null;
107
+ async function cachedCatalog() {
108
+ if (!(await exists(catalogPath)) || !(await exists(catalogMetaPath)))
109
+ return null;
110
+ const meta = JSON.parse(await readFile(catalogMetaPath, 'utf8'));
111
+ if (!customFetch && (meta.repositoryUrl !== repositoryUrl(options) || meta.ref !== String(options.ref ?? DEFAULT_REF)))
112
+ return null;
113
+ activeRevision = meta.revision ?? null;
114
+ if (!customFetch)
115
+ activeGitDir = await ensureGitRepository(cacheRoot, options);
116
+ return JSON.parse(await readFile(catalogPath, 'utf8'));
117
+ }
118
+ async function refreshCatalog() {
119
+ let catalog;
120
+ let revision;
121
+ if (options.fetchCatalog) {
122
+ catalog = await options.fetchCatalog();
123
+ revision = String(catalog.repositoryRevision ?? catalog.package?.version ?? 'custom');
124
+ }
125
+ else {
126
+ const fetched = await fetchGitRevision(cacheRoot, options);
127
+ activeGitDir = fetched.gitDir;
128
+ revision = fetched.revision;
129
+ const rawCatalog = JSON.parse(await readGitFile(activeGitDir, revision, 'catalog.json'));
130
+ catalog = {
131
+ ...rawCatalog,
132
+ repositoryRevision: revision,
133
+ entries: (rawCatalog.entries ?? []).map((entry) => ({ ...entry, revision })),
134
+ };
135
+ }
136
+ activeRevision = revision;
137
+ await mkdir(cacheRoot, { recursive: true });
138
+ await writeFile(catalogPath, `${JSON.stringify(catalog, null, 2)}\n`, 'utf8');
139
+ await writeFile(catalogMetaPath, `${JSON.stringify({
140
+ revision,
141
+ ref: String(options.ref ?? DEFAULT_REF),
142
+ repositoryUrl: customFetch ? 'custom' : repositoryUrl(options),
143
+ }, null, 2)}\n`, 'utf8');
144
+ return catalog;
145
+ }
146
+ async function revisionForModule() {
147
+ if (activeRevision)
148
+ return activeRevision;
149
+ const catalog = await cachedCatalog();
150
+ if (catalog && activeRevision)
151
+ return activeRevision;
152
+ await refreshCatalog();
153
+ return activeRevision;
154
+ }
155
+ return {
156
+ cacheRoot,
157
+ cachedModulePath(id, version) { return join(cacheRoot, 'rules', id, version); },
158
+ async hasModule(id, version, contentHash = null) {
159
+ const marker = await readMarker(join(cacheRoot, 'rules', id, version, '.complete'));
160
+ return markerMatches(marker, id, version, contentHash);
161
+ },
162
+ async catalog({ refresh = false } = {}) {
163
+ if (!refresh) {
164
+ const cached = await cachedCatalog();
165
+ if (cached)
166
+ return cached;
167
+ }
168
+ return await refreshCatalog();
169
+ },
170
+ async module(id, version, { refresh = false, contentHash = null } = {}) {
171
+ const root = join(cacheRoot, 'rules', id, version);
172
+ const markerPath = join(root, '.complete');
173
+ const marker = await readMarker(markerPath);
174
+ if (!refresh && markerMatches(marker, id, version, contentHash))
175
+ return root;
176
+ const revision = await revisionForModule();
177
+ let payload;
178
+ if (options.fetchModule)
179
+ payload = await options.fetchModule(id, { revision });
180
+ else {
181
+ activeGitDir ??= await ensureGitRepository(cacheRoot, options);
182
+ payload = await readGitModule(activeGitDir, revision, id);
183
+ }
184
+ await rm(root, { recursive: true, force: true });
185
+ await mkdir(root, { recursive: true });
186
+ await writePayload(root, payload.files ?? []);
187
+ await writeFile(markerPath, `${JSON.stringify({ id, version, contentHash, revision })}\n`, 'utf8');
188
+ return root;
189
+ },
190
+ };
191
+ }
192
+ async function directoryFiles(root, prefix = '') {
193
+ const files = [];
194
+ for (const entry of (await readdir(root, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
195
+ if (entry.name === '.complete')
196
+ continue;
197
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
198
+ if (entry.isDirectory())
199
+ files.push(...await directoryFiles(join(root, entry.name), relative));
200
+ else if (entry.isFile())
201
+ files.push({ path: relative, content: await readFile(join(root, entry.name), 'utf8') });
202
+ }
203
+ return files;
204
+ }
205
+ export async function fetchGitHubCatalog(options = {}) {
206
+ return await createCanonicalSource(options).catalog({ refresh: true });
207
+ }
208
+ export async function fetchGitHubModule(id, options = {}) {
209
+ const source = createCanonicalSource(options);
210
+ const catalog = await source.catalog({ refresh: true });
211
+ const entry = (catalog.entries ?? []).find((candidate) => candidate.id === id);
212
+ if (!entry)
213
+ throw new Error(`Canonical module not found in catalog: ${id}`);
214
+ const root = await source.module(id, entry.version, { contentHash: entry.contentHash });
215
+ return { files: await directoryFiles(root) };
216
+ }
@@ -0,0 +1,47 @@
1
+ export function buildCatalogSnapshot(): Promise<{
2
+ package: {
3
+ name: any;
4
+ version: any;
5
+ };
6
+ entries: {
7
+ source: string;
8
+ projectProfiles?: {
9
+ [k: string]: {
10
+ ruleIds: any[];
11
+ };
12
+ } | undefined;
13
+ notApplicableRuleIds?: any[] | undefined;
14
+ composedOf?: string[] | undefined;
15
+ verification?: any;
16
+ ai?: any;
17
+ requiredCapabilities?: string[] | undefined;
18
+ requiredPackages?: string[] | undefined;
19
+ applicableStacks?: any[] | undefined;
20
+ enforcement?: string | undefined;
21
+ legacyInstalledIds?: any[] | undefined;
22
+ order: number;
23
+ revision: string;
24
+ contentHash: string;
25
+ labels?: string[] | undefined;
26
+ scope?: string | undefined;
27
+ category?: string | undefined;
28
+ summary?: any;
29
+ id: any;
30
+ kind: any;
31
+ version: string;
32
+ name: any;
33
+ content: any;
34
+ }[];
35
+ predefinedPackages: {
36
+ id: string;
37
+ recipeVersion: string;
38
+ role: string;
39
+ requires: string[];
40
+ conflicts: string[];
41
+ variants: {
42
+ id: string;
43
+ when: string[];
44
+ }[];
45
+ }[];
46
+ schemaVersion: number;
47
+ }>;
@@ -0,0 +1,28 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { buildGitCatalog } from './git-catalog.js';
4
+ import { listPackageRecipes } from "./predefined-packages/registry.js";
5
+ const MODULES_ROOT = fileURLToPath(new URL('../modules/', import.meta.url));
6
+ export async function buildCatalogSnapshot() {
7
+ const packageJson = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
8
+ const catalog = await buildGitCatalog({ modulesRoot: MODULES_ROOT, repositoryRevision: packageJson.version });
9
+ return {
10
+ ...catalog,
11
+ package: { name: packageJson.name, version: packageJson.version },
12
+ entries: catalog.entries
13
+ .map((entry) => ({ ...entry, source: '@specdest/devkit' }))
14
+ .sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
15
+ predefinedPackages: listPackageRecipes()
16
+ .map((recipe) => ({
17
+ id: recipe.id,
18
+ recipeVersion: recipe.recipeVersion,
19
+ role: recipe.role,
20
+ requires: [...(recipe.requires ?? [])].sort(),
21
+ conflicts: [...(recipe.conflicts ?? [])].sort(),
22
+ variants: (recipe.variants ?? [])
23
+ .map((variant) => ({ id: variant.id, when: [...variant.when].sort() }))
24
+ .sort((a, b) => a.id.localeCompare(b.id)),
25
+ }))
26
+ .sort((a, b) => a.id.localeCompare(b.id)),
27
+ };
28
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import { createFlowCommandHandler, createFuzzCommandHandler, runCli } from "./index.js";
3
+ import { createCanonicalCommandHandlers } from "./canonical-project-operations.js";
4
+ try {
5
+ const exitCode = await runCli(process.argv.slice(2), process, {
6
+ ...createCanonicalCommandHandlers(),
7
+ fuzz: createFuzzCommandHandler(),
8
+ flow: createFlowCommandHandler(),
9
+ });
10
+ process.exitCode = exitCode;
11
+ }
12
+ catch (error) {
13
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
14
+ process.exitCode = 1;
15
+ }
@@ -0,0 +1,9 @@
1
+ export declare function createCanonicalCommandHandlers(projectRoot?: string, options?: any): {
2
+ add: (args: string[], io: any) => Promise<0 | 1 | 2>;
3
+ status: (args: string[], io: any) => Promise<0 | 1>;
4
+ sync: (args: string[], io: any) => Promise<0 | 2>;
5
+ check: (args: string[], io: any) => Promise<number>;
6
+ rules: (args: string[], io: any) => Promise<number>;
7
+ 'ai-instruction': (args: string[], io: any) => Promise<0 | 2>;
8
+ doctor: (args: string[], io: any) => Promise<0 | 1 | 2>;
9
+ };