@specdest/devkit 0.2.1 → 0.3.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.
Files changed (138) hide show
  1. package/README.md +15 -20
  2. package/package.json +4 -4
  3. package/src/canonical-project-operations.js +157 -0
  4. package/src/canonical-project.js +50 -0
  5. package/src/canonical-source.js +114 -0
  6. package/src/cli.js +2 -2
  7. package/src/git-catalog.js +105 -0
  8. package/src/index.js +6 -2
  9. package/src/project-operations.js +69 -9
  10. package/src/remote-installer.js +462 -0
  11. package/src/sync-core.js +26 -10
  12. package/catalog/README.md +0 -11
  13. package/catalog/modules/backend-convex/manifest.json +0 -14
  14. package/catalog/modules/backend-convex-expo/manifest.json +0 -11
  15. package/catalog/modules/backend-supabase/manifest.json +0 -15
  16. package/catalog/modules/backend-supabase-expo/manifest.json +0 -11
  17. package/catalog/modules/checker-runtime/config.ts +0 -25
  18. package/catalog/modules/checker-runtime/fs.ts +0 -48
  19. package/catalog/modules/checker-runtime/manifest.json +0 -28
  20. package/catalog/modules/checker-runtime/runtime.ts +0 -79
  21. package/catalog/modules/devflow/.agents/skills/devflow/SKILL.md +0 -33
  22. package/catalog/modules/devflow/.devflow.json +0 -10
  23. package/catalog/modules/devflow/manifest.json +0 -35
  24. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/SKILL.md +0 -85
  25. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/activeScenario.mjs +0 -130
  26. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/checkLocalEnvironment.mjs +0 -7
  27. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/completeActiveScenario.mjs +0 -36
  28. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/createActiveScenario.mjs +0 -143
  29. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/localEnvironment.mjs +0 -43
  30. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/prompt.mjs +0 -25
  31. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/runActiveScenario.mjs +0 -66
  32. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/runAuthoringScenario.mjs +0 -146
  33. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/seed.mjs +0 -56
  34. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/seedActiveScenario.mjs +0 -6
  35. package/catalog/modules/e2e-playwright/docs/e2e-playwright/README.md +0 -103
  36. package/catalog/modules/e2e-playwright/manifest.json +0 -206
  37. package/catalog/modules/e2e-playwright/playwright.e2e.config.ts +0 -39
  38. package/catalog/modules/e2e-playwright/tests/e2e/support/e2ePlaywrightFlow.ts +0 -107
  39. package/catalog/modules/e2e-playwright/tests/e2e/support/fixtures.ts +0 -27
  40. package/catalog/modules/local-log/AGENTS.local-log.md +0 -13
  41. package/catalog/modules/local-log/docs/features/local-logging/README.md +0 -70
  42. package/catalog/modules/local-log/manifest.json +0 -39
  43. package/catalog/modules/local-log/tmp/logs/.gitignore +0 -2
  44. package/catalog/modules/local-log/tools/local-log/README.md +0 -47
  45. package/catalog/modules/local-log/tools/local-log/local-log.mjs +0 -241
  46. package/catalog/modules/stack-common-vite/manifest.json +0 -16
  47. package/catalog/modules/stack-expo-convex/manifest.json +0 -31
  48. package/catalog/modules/stack-expo-supabase/manifest.json +0 -44
  49. package/catalog/modules/stack-vite-convex/manifest.json +0 -32
  50. package/catalog/modules/stack-vite-supabase/manifest.json +0 -45
  51. package/catalog/rules/abac-permissions-convex/SKILL.md +0 -17
  52. package/catalog/rules/abac-permissions-convex/check.ts +0 -87
  53. package/catalog/rules/abac-permissions-convex/manifest.json +0 -33
  54. package/catalog/rules/abac-permissions-supabase/SKILL.md +0 -17
  55. package/catalog/rules/abac-permissions-supabase/check.ts +0 -87
  56. package/catalog/rules/abac-permissions-supabase/manifest.json +0 -33
  57. package/catalog/rules/convex-multi-presentation/SKILL.md +0 -47
  58. package/catalog/rules/convex-multi-presentation/check.ts +0 -205
  59. package/catalog/rules/convex-multi-presentation/manifest.json +0 -47
  60. package/catalog/rules/convex-multi-presentation/policy.ts +0 -261
  61. package/catalog/rules/design-rules/SKILL.md +0 -12
  62. package/catalog/rules/design-rules/check.ts +0 -84
  63. package/catalog/rules/design-rules/config.json +0 -5
  64. package/catalog/rules/design-rules/manifest.json +0 -38
  65. package/catalog/rules/e2e-test-rules/SKILL.md +0 -46
  66. package/catalog/rules/e2e-test-rules/check.ts +0 -145
  67. package/catalog/rules/e2e-test-rules/config.json +0 -32
  68. package/catalog/rules/e2e-test-rules/manifest.json +0 -38
  69. package/catalog/rules/error-handling-rules/SKILL.md +0 -21
  70. package/catalog/rules/error-handling-rules/check.ts +0 -73
  71. package/catalog/rules/error-handling-rules/manifest.json +0 -33
  72. package/catalog/rules/layers-and-contracts/SKILL.md +0 -36
  73. package/catalog/rules/layers-and-contracts/check.ts +0 -266
  74. package/catalog/rules/layers-and-contracts/manifest.json +0 -33
  75. package/catalog/rules/layers-and-contracts-convex/SKILL.md +0 -49
  76. package/catalog/rules/layers-and-contracts-convex/check.ts +0 -289
  77. package/catalog/rules/layers-and-contracts-convex/manifest.json +0 -38
  78. package/catalog/rules/layers-and-contracts-convex/policy.ts +0 -68
  79. package/catalog/rules/layers-and-contracts-supabase/SKILL.md +0 -52
  80. package/catalog/rules/layers-and-contracts-supabase/check.ts +0 -371
  81. package/catalog/rules/layers-and-contracts-supabase/manifest.json +0 -38
  82. package/catalog/rules/layers-and-contracts-supabase/policy.ts +0 -68
  83. package/catalog/rules/module-size-rules/SKILL.md +0 -5
  84. package/catalog/rules/module-size-rules/check.ts +0 -144
  85. package/catalog/rules/module-size-rules/config.json +0 -6
  86. package/catalog/rules/module-size-rules/manifest.json +0 -38
  87. package/catalog/rules/module-size-rules-convex/SKILL.md +0 -5
  88. package/catalog/rules/module-size-rules-convex/check.ts +0 -146
  89. package/catalog/rules/module-size-rules-convex/config.json +0 -6
  90. package/catalog/rules/module-size-rules-convex/manifest.json +0 -38
  91. package/catalog/rules/module-size-rules-supabase/SKILL.md +0 -5
  92. package/catalog/rules/module-size-rules-supabase/check.ts +0 -146
  93. package/catalog/rules/module-size-rules-supabase/config.json +0 -12
  94. package/catalog/rules/module-size-rules-supabase/manifest.json +0 -38
  95. package/catalog/rules/mutation-command-rules/SKILL.md +0 -15
  96. package/catalog/rules/mutation-command-rules/check.ts +0 -30
  97. package/catalog/rules/mutation-command-rules/config.json +0 -19
  98. package/catalog/rules/mutation-command-rules/manifest.json +0 -38
  99. package/catalog/rules/nearby-contracts/SKILL.md +0 -18
  100. package/catalog/rules/nearby-contracts/check.ts +0 -138
  101. package/catalog/rules/nearby-contracts/config.json +0 -10
  102. package/catalog/rules/nearby-contracts/manifest.json +0 -38
  103. package/catalog/rules/no-raw-click-buttons/SKILL.md +0 -5
  104. package/catalog/rules/no-raw-click-buttons/check.ts +0 -37
  105. package/catalog/rules/no-raw-click-buttons/manifest.json +0 -33
  106. package/catalog/rules/public-api-export-barrels/SKILL.md +0 -45
  107. package/catalog/rules/public-api-export-barrels/check.ts +0 -73
  108. package/catalog/rules/public-api-export-barrels/config.json +0 -4
  109. package/catalog/rules/public-api-export-barrels/manifest.json +0 -38
  110. package/catalog/rules/route-tree-fresh/SKILL.md +0 -16
  111. package/catalog/rules/route-tree-fresh/check.ts +0 -66
  112. package/catalog/rules/route-tree-fresh/manifest.json +0 -33
  113. package/catalog/rules/strict-typescript/SKILL.md +0 -3
  114. package/catalog/rules/strict-typescript/check.ts +0 -119
  115. package/catalog/rules/strict-typescript/manifest.json +0 -33
  116. package/catalog/rules/supabase-contracts/SKILL.md +0 -3
  117. package/catalog/rules/supabase-contracts/check.ts +0 -172
  118. package/catalog/rules/supabase-contracts/manifest.json +0 -33
  119. package/catalog/rules/supabase-declarative-schema/SKILL.md +0 -30
  120. package/catalog/rules/supabase-declarative-schema/check.ts +0 -262
  121. package/catalog/rules/supabase-declarative-schema/config.json +0 -8
  122. package/catalog/rules/supabase-declarative-schema/manifest.json +0 -38
  123. package/catalog/rules/tanstack-form-rules/SKILL.md +0 -11
  124. package/catalog/rules/tanstack-form-rules/check.ts +0 -58
  125. package/catalog/rules/tanstack-form-rules/manifest.json +0 -33
  126. package/catalog/rules/unit-test-rules/SKILL.md +0 -55
  127. package/catalog/rules/unit-test-rules/check.ts +0 -132
  128. package/catalog/rules/unit-test-rules/config.json +0 -22
  129. package/catalog/rules/unit-test-rules/manifest.json +0 -38
  130. package/catalog/rules/unit-test-rules-convex/SKILL.md +0 -41
  131. package/catalog/rules/unit-test-rules-convex/check.ts +0 -418
  132. package/catalog/rules/unit-test-rules-convex/manifest.json +0 -33
  133. package/catalog/rules/unit-test-rules-supabase/SKILL.md +0 -40
  134. package/catalog/rules/unit-test-rules-supabase/check.ts +0 -492
  135. package/catalog/rules/unit-test-rules-supabase/manifest.json +0 -33
  136. package/catalog/rules/workstation-controller-rules/SKILL.md +0 -22
  137. package/catalog/rules/workstation-controller-rules/check.ts +0 -108
  138. package/catalog/rules/workstation-controller-rules/manifest.json +0 -33
@@ -0,0 +1,462 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises';
4
+ import { dirname, isAbsolute, resolve, sep } from 'node:path';
5
+
6
+ import { removeMarkdownSection, resolveProjectPath, upsertMarkdownSection } from './installer-primitives.js';
7
+
8
+ const INSTALLED_PATH = '.specdest/installed.json';
9
+ const STATE_PATH = '.specdest/state.json';
10
+ const SCRIPT_PHASES = new Set(['pre_install', 'post_install', 'pre_sync', 'post_sync', 'pre_remove', 'post_remove']);
11
+ const OP_TYPES = new Set(['copy_file', 'copy_directory', 'managed_section', 'json_set', 'json_merge', 'yaml_set', 'yaml_merge', 'env_set', 'env_remove', 'delete_owned_artifact', 'run_custom_script', 'run_script_file']);
12
+ const clone = (value) => value === undefined ? undefined : JSON.parse(JSON.stringify(value));
13
+ const hash = (value) => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value)).digest('hex');
14
+ const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
15
+
16
+ function payloadPath(payloadRoot, relativePath) {
17
+ if (!relativePath || isAbsolute(relativePath)) throw new Error(`Source must be payload-relative: ${relativePath}`);
18
+ const root = resolve(payloadRoot);
19
+ const target = resolve(root, relativePath);
20
+ if (target !== root && !target.startsWith(`${root}${sep}`)) throw new Error(`Source escapes payload: ${relativePath}`);
21
+ return target;
22
+ }
23
+
24
+ async function exists(path) {
25
+ try { await stat(path); return true; } catch (error) { if (error?.code === 'ENOENT') return false; throw error; }
26
+ }
27
+
28
+ async function readJsonState(root, relativePath, fallback, label) {
29
+ try {
30
+ const parsed = JSON.parse(await readFile(resolveProjectPath(root, relativePath), 'utf8'));
31
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(`Invalid ${label} state`);
32
+ return parsed;
33
+ } catch (error) {
34
+ if (error?.code === 'ENOENT') return clone(fallback);
35
+ throw error;
36
+ }
37
+ }
38
+
39
+ async function writeJsonState(root, relativePath, state) {
40
+ const target = resolveProjectPath(root, relativePath);
41
+ await mkdir(dirname(target), { recursive: true });
42
+ const temp = `${target}.${process.pid}.tmp`;
43
+ await writeFile(temp, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
44
+ await rename(temp, target);
45
+ }
46
+
47
+ async function readInstalledState(root) {
48
+ const state = await readJsonState(root, INSTALLED_PATH, { schemaVersion: 2, requested: [], installed: {} }, 'installed');
49
+ if (!state.installed || typeof state.installed !== 'object' || Array.isArray(state.installed)) throw new Error('Invalid installed state');
50
+ if (!Array.isArray(state.requested)) state.requested = [];
51
+ return state;
52
+ }
53
+
54
+ async function readRuntimeState(root) {
55
+ const state = await readJsonState(root, STATE_PATH, { schemaVersion: 2, results: {}, ownership: {} }, 'runtime');
56
+ if (!state.results || typeof state.results !== 'object' || Array.isArray(state.results)) state.results = {};
57
+ if (!state.ownership || typeof state.ownership !== 'object' || Array.isArray(state.ownership)) state.ownership = {};
58
+ return state;
59
+ }
60
+
61
+ const checkerSkillIds = new Map([
62
+ ['abac-permissions-convex', 'abac-permissions'],
63
+ ['abac-permissions-supabase', 'abac-permissions'],
64
+ ['unit-test-rules-convex', 'unit-test-rules'],
65
+ ['unit-test-rules-supabase', 'unit-test-rules'],
66
+ ]);
67
+
68
+ function checkerSkillId(implementation) {
69
+ return checkerSkillIds.get(implementation) ?? implementation;
70
+ }
71
+
72
+ function normalizeManifest(manifest) {
73
+ const operations = Array.isArray(manifest?.operations) ? [...manifest.operations] : [];
74
+ const checkerImplementation = String(manifest?.checker?.implementation ?? "").trim();
75
+ const check = manifest?.check ?? (checkerImplementation
76
+ ? { command: ["node", `.agents/skills/${checkerSkillId(checkerImplementation)}/check.ts`] }
77
+ : undefined);
78
+ for (const copy of manifest?.copies ?? []) {
79
+ operations.push({
80
+ type: copy.type === 'directory' || copy.directory === true ? 'copy_directory' : 'copy_file',
81
+ source: copy.source,
82
+ path: copy.target ?? copy.path,
83
+ mode: copy.mode,
84
+ });
85
+ }
86
+ for (const section of manifest?.markdownSections ?? []) {
87
+ operations.push({ type: 'managed_section', path: section.path, heading: section.heading, content: section.body ?? section.content ?? '' });
88
+ }
89
+ return { ...manifest, operations, ...(check ? { check } : {}) };
90
+ }
91
+
92
+ export function validateRemoteManifest(input) {
93
+ if (!input || typeof input !== 'object' || !String(input.id ?? '').trim()) throw new Error('Manifest id is required');
94
+ const manifest = normalizeManifest(input);
95
+ if (!Array.isArray(manifest.operations)) throw new Error(`Manifest operations must be an array: ${manifest.id}`);
96
+ for (const op of manifest.operations) {
97
+ if (!OP_TYPES.has(op?.type)) throw new Error(`Unsupported manifest operation: ${op?.type}`);
98
+ if (op.type.startsWith('run_')) {
99
+ if (!SCRIPT_PHASES.has(op.phase)) throw new Error(`Script operation must declare a valid lifecycle phase: ${op.type}`);
100
+ } else if (op.path) resolveProjectPath('/__specdest_project__', op.path);
101
+ }
102
+ return manifest;
103
+ }
104
+
105
+ function getAt(root, keyPath) {
106
+ let current = root;
107
+ for (const key of keyPath) {
108
+ if (!current || typeof current !== 'object' || Array.isArray(current) || !hasOwn(current, key)) return { exists: false, value: undefined };
109
+ current = current[key];
110
+ }
111
+ return { exists: true, value: current };
112
+ }
113
+
114
+ function setAt(root, keyPath, value) {
115
+ let current = root;
116
+ for (const key of keyPath.slice(0, -1)) {
117
+ if (!hasOwn(current, key)) current[key] = {};
118
+ if (!current[key] || typeof current[key] !== 'object' || Array.isArray(current[key])) throw new Error(`Cannot set nested key through non-object: ${keyPath.join('.')}`);
119
+ current = current[key];
120
+ }
121
+ current[keyPath.at(-1)] = clone(value);
122
+ }
123
+
124
+ function deleteAt(root, keyPath) {
125
+ let current = root;
126
+ for (const key of keyPath.slice(0, -1)) {
127
+ if (!current || typeof current !== 'object' || !hasOwn(current, key)) return;
128
+ current = current[key];
129
+ }
130
+ if (current && typeof current === 'object') delete current[keyPath.at(-1)];
131
+ }
132
+
133
+ function leaves(value, prefix = []) {
134
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
135
+ return Object.entries(value).flatMap(([key, nested]) => leaves(nested, [...prefix, key]));
136
+ }
137
+ return [[prefix, value]];
138
+ }
139
+
140
+ function scalarFromYaml(raw) {
141
+ const value = raw.trim();
142
+ if (value === 'true') return true;
143
+ if (value === 'false') return false;
144
+ if (value === 'null' || value === '~') return null;
145
+ if (/^-?\d+(\.\d+)?$/u.test(value)) return Number(value);
146
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) return value.slice(1, -1);
147
+ return value;
148
+ }
149
+
150
+ function parseYaml(text) {
151
+ const root = {};
152
+ const stack = [{ indent: -1, object: root }];
153
+ for (const raw of text.replace(/\r\n/g, '\n').split('\n')) {
154
+ if (!raw.trim() || raw.trimStart().startsWith('#')) continue;
155
+ const indent = raw.match(/^ */u)?.[0].length ?? 0;
156
+ const match = raw.trim().match(/^([^:#][^:]*):(?:\s*(.*))?$/u);
157
+ if (!match) throw new Error(`Unsupported YAML syntax: ${raw.trim()}`);
158
+ while (stack.length > 1 && indent <= stack.at(-1).indent) stack.pop();
159
+ const object = stack.at(-1).object;
160
+ const key = match[1].trim();
161
+ const rest = match[2] ?? '';
162
+ if (!rest) {
163
+ object[key] = {};
164
+ stack.push({ indent, object: object[key] });
165
+ } else object[key] = scalarFromYaml(rest);
166
+ }
167
+ return root;
168
+ }
169
+
170
+ function yamlScalar(value) {
171
+ if (value === null) return 'null';
172
+ if (typeof value === 'boolean' || typeof value === 'number') return String(value);
173
+ const text = String(value);
174
+ return /^[A-Za-z0-9_./@-]+$/u.test(text) ? text : JSON.stringify(text);
175
+ }
176
+
177
+ function stringifyYaml(object, indent = 0) {
178
+ const lines = [];
179
+ for (const [key, value] of Object.entries(object)) {
180
+ const prefix = ' '.repeat(indent);
181
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
182
+ lines.push(`${prefix}${key}:`);
183
+ lines.push(stringifyYaml(value, indent + 2).trimEnd());
184
+ } else if (Array.isArray(value)) {
185
+ lines.push(`${prefix}${key}: ${JSON.stringify(value)}`);
186
+ } else lines.push(`${prefix}${key}: ${yamlScalar(value)}`);
187
+ }
188
+ return `${lines.filter(Boolean).join('\n')}\n`;
189
+ }
190
+
191
+ function envMap(text) {
192
+ const map = new Map();
193
+ for (const line of text.replace(/\r\n/g, '\n').split('\n')) {
194
+ const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/u);
195
+ if (match) map.set(match[1], match[2]);
196
+ }
197
+ return map;
198
+ }
199
+
200
+ function setEnv(text, key, value) {
201
+ const lines = text.replace(/\r\n/g, '\n').split('\n').filter((line) => !new RegExp(`^${key}=`).test(line));
202
+ while (lines.length && lines.at(-1) === '') lines.pop();
203
+ lines.push(`${key}=${value}`);
204
+ return `${lines.join('\n')}\n`;
205
+ }
206
+
207
+ function removeEnv(text, key) {
208
+ const lines = text.replace(/\r\n/g, '\n').split('\n').filter((line) => !new RegExp(`^${key}=`).test(line));
209
+ while (lines.length && lines.at(-1) === '') lines.pop();
210
+ return lines.length ? `${lines.join('\n')}\n` : '';
211
+ }
212
+
213
+ function markdownSection(text, heading) {
214
+ const lines = text.split(/(?<=\n)/u);
215
+ const level = heading.trim().match(/^(#{1,6})\s/u)?.[1].length ?? 2;
216
+ let start = -1; let end = text.length; let offset = 0;
217
+ for (const line of lines) {
218
+ if (start < 0 && line.trim() === heading.trim()) start = offset;
219
+ else if (start >= 0 && new RegExp(`^#{1,${level}}\\s+`).test(line.trim())) { end = offset; break; }
220
+ offset += line.length;
221
+ }
222
+ return start < 0 ? { exists: false, value: '' } : { exists: true, value: text.slice(start, end).trimEnd() };
223
+ }
224
+
225
+ function ownershipKey(type, path, scope = '') { return `${type}:${path}${scope ? `:${scope}` : ''}`; }
226
+ function fingerprint(found) { return hash({ exists: found.exists, value: found.value }); }
227
+ function assertFingerprint(record, current, label) {
228
+ if (record.appliedHash !== fingerprint(current)) throw new Error(`Conflict: user-modified owned content at ${label}`);
229
+ }
230
+
231
+ async function writeText(root, path, content) {
232
+ const target = resolveProjectPath(root, path);
233
+ await mkdir(dirname(target), { recursive: true });
234
+ await writeFile(target, content, 'utf8');
235
+ }
236
+
237
+ async function readText(root, path) {
238
+ const target = resolveProjectPath(root, path);
239
+ return await exists(target) ? await readFile(target, 'utf8') : '';
240
+ }
241
+
242
+ async function executeHook(op, { projectRoot, payloadRoot, executor }) {
243
+ const cwd = op.cwd ? resolveProjectPath(projectRoot, op.cwd) : projectRoot;
244
+ let command; let args;
245
+ if (op.type === 'run_custom_script') {
246
+ command = op.command;
247
+ args = op.args ?? [];
248
+ } else {
249
+ const source = payloadPath(payloadRoot, op.source);
250
+ command = op.command ?? source;
251
+ args = op.command ? [source, ...(op.args ?? [])] : (op.args ?? []);
252
+ }
253
+ if (!String(command ?? '').trim()) throw new Error(`Script command is required: ${op.type}`);
254
+ const run = executor ?? ((cmd, argv, options) => new Promise((resolveRun, reject) => {
255
+ const child = spawn(cmd, argv, { cwd: options.cwd, stdio: 'inherit', shell: false });
256
+ child.on('error', reject);
257
+ child.on('close', (code) => resolveRun(code ?? 1));
258
+ }));
259
+ const code = await run(command, args, { cwd });
260
+ if (code !== 0) throw new Error(`${op.type} exited with code ${code}`);
261
+ }
262
+
263
+ async function runPhase(manifest, phase, context) {
264
+ for (const op of manifest.operations) if (op.type.startsWith('run_') && op.phase === phase) await executeHook(op, context);
265
+ }
266
+
267
+ async function currentForRecord(root, record) {
268
+ if (record.type === 'file') {
269
+ const target = resolveProjectPath(root, record.path);
270
+ return await exists(target) ? { exists: true, value: await readFile(target, 'utf8') } : { exists: false, value: undefined };
271
+ }
272
+ const text = await readText(root, record.path);
273
+ if (record.type === 'markdown') return markdownSection(text, record.heading);
274
+ if (record.type === 'env') {
275
+ const map = envMap(text);
276
+ return { exists: map.has(record.key), value: map.get(record.key) };
277
+ }
278
+ const object = record.type === 'json' ? (text.trim() ? JSON.parse(text) : {}) : parseYaml(text);
279
+ return getAt(object, record.keyPath);
280
+ }
281
+
282
+ async function restoreRecord(root, record, { deleteInstead = false } = {}) {
283
+ const current = await currentForRecord(root, record);
284
+ assertFingerprint(record, current, record.path);
285
+ if (record.type === 'file') {
286
+ const target = resolveProjectPath(root, record.path);
287
+ if (deleteInstead || !record.previousExists) { if (await exists(target)) await unlink(target); }
288
+ else await writeText(root, record.path, record.previousValue);
289
+ return;
290
+ }
291
+ if (record.type === 'markdown') {
292
+ const text = await readText(root, record.path);
293
+ const updated = record.previousExists && !deleteInstead
294
+ ? upsertMarkdownSection(text, record.heading, String(record.previousValue).replace(/^#{1,6}\s+.*?\n+/u, ''))
295
+ : removeMarkdownSection(text, record.heading);
296
+ await writeText(root, record.path, updated);
297
+ return;
298
+ }
299
+ if (record.type === 'env') {
300
+ let text = await readText(root, record.path);
301
+ text = record.previousExists && !deleteInstead ? setEnv(text, record.key, record.previousValue) : removeEnv(text, record.key);
302
+ await writeText(root, record.path, text);
303
+ return;
304
+ }
305
+ const text = await readText(root, record.path);
306
+ const object = record.type === 'json' ? (text.trim() ? JSON.parse(text) : {}) : parseYaml(text);
307
+ if (record.previousExists && !deleteInstead) setAt(object, record.keyPath, record.previousValue); else deleteAt(object, record.keyPath);
308
+ await writeText(root, record.path, record.type === 'json' ? `${JSON.stringify(object, null, 2)}\n` : stringifyYaml(object));
309
+ }
310
+
311
+ async function claimFile(context, sourcePath, destination, touched) {
312
+ const content = await readFile(sourcePath, 'utf8');
313
+ const key = ownershipKey('file', destination);
314
+ const prior = context.prior[key];
315
+ const target = resolveProjectPath(context.projectRoot, destination);
316
+ const current = await exists(target) ? { exists: true, value: await readFile(target, 'utf8') } : { exists: false, value: undefined };
317
+ if (prior) assertFingerprint(prior, current, destination);
318
+ const original = prior ?? { previousExists: current.exists, previousValue: current.value };
319
+ await writeText(context.projectRoot, destination, content);
320
+ context.next[key] = { type: 'file', path: destination, previousExists: original.previousExists, previousValue: original.previousValue, appliedHash: fingerprint({ exists: true, value: content }) };
321
+ touched.add(key);
322
+ }
323
+
324
+ async function applyOperation(op, context, touched) {
325
+ const { projectRoot, payloadRoot } = context;
326
+ if (op.type === 'copy_file') return claimFile(context, payloadPath(payloadRoot, op.source), op.path, touched);
327
+ if (op.type === 'copy_directory') {
328
+ const sourceRoot = payloadPath(payloadRoot, op.source);
329
+ const walk = async (dir, prefix = '') => {
330
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
331
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
332
+ if (entry.isDirectory()) await walk(resolve(dir, entry.name), relative);
333
+ else if (entry.isFile()) await claimFile(context, resolve(dir, entry.name), `${op.path.replace(/\/$/u, '')}/${relative}`, touched);
334
+ }
335
+ };
336
+ return walk(sourceRoot);
337
+ }
338
+ if (op.type === 'delete_owned_artifact') {
339
+ const matches = Object.entries(context.next).filter(([, record]) => record.path === op.path && record.type === 'file');
340
+ if (!matches.length) throw new Error(`Artifact is not owned: ${op.path}`);
341
+ for (const [key, record] of matches) { await restoreRecord(projectRoot, record, { deleteInstead: true }); delete context.next[key]; touched.add(key); }
342
+ return;
343
+ }
344
+ if (op.type === 'managed_section') {
345
+ const key = ownershipKey('markdown', op.path, op.heading);
346
+ const prior = context.prior[key];
347
+ const text = await readText(projectRoot, op.path);
348
+ const current = markdownSection(text, op.heading);
349
+ if (prior) assertFingerprint(prior, current, op.path);
350
+ const original = prior ?? { previousExists: current.exists, previousValue: current.value };
351
+ const updated = upsertMarkdownSection(text, op.heading, op.content ?? '');
352
+ await writeText(projectRoot, op.path, updated);
353
+ const applied = markdownSection(updated, op.heading);
354
+ context.next[key] = { type: 'markdown', path: op.path, heading: op.heading, previousExists: original.previousExists, previousValue: original.previousValue, appliedHash: fingerprint(applied) };
355
+ touched.add(key); return;
356
+ }
357
+ if (op.type === 'env_set' || op.type === 'env_remove') {
358
+ const key = ownershipKey('env', op.path, op.key);
359
+ const prior = context.prior[key];
360
+ let text = await readText(projectRoot, op.path);
361
+ const map = envMap(text);
362
+ const current = { exists: map.has(op.key), value: map.get(op.key) };
363
+ if (prior) assertFingerprint(prior, current, op.path);
364
+ const original = prior ?? { previousExists: current.exists, previousValue: current.value };
365
+ text = op.type === 'env_set' ? setEnv(text, op.key, String(op.value ?? '')) : removeEnv(text, op.key);
366
+ await writeText(projectRoot, op.path, text);
367
+ const updatedMap = envMap(text);
368
+ context.next[key] = { type: 'env', path: op.path, key: op.key, previousExists: original.previousExists, previousValue: original.previousValue, appliedHash: fingerprint({ exists: updatedMap.has(op.key), value: updatedMap.get(op.key) }) };
369
+ touched.add(key); return;
370
+ }
371
+ if (['json_set', 'json_merge', 'yaml_set', 'yaml_merge'].includes(op.type)) {
372
+ const type = op.type.startsWith('json') ? 'json' : 'yaml';
373
+ const text = await readText(projectRoot, op.path);
374
+ const object = type === 'json' ? (text.trim() ? JSON.parse(text) : {}) : parseYaml(text);
375
+ const assignments = op.type.endsWith('_set') ? [[op.keyPath, op.value]] : leaves(op.value);
376
+ for (const [keyPath, value] of assignments) {
377
+ if (!Array.isArray(keyPath) || !keyPath.length) throw new Error(`Structured operation requires keyPath/value leaves: ${op.path}`);
378
+ const key = ownershipKey(type, op.path, keyPath.join('.'));
379
+ const prior = context.prior[key];
380
+ const current = getAt(object, keyPath);
381
+ if (prior) assertFingerprint(prior, current, op.path);
382
+ const original = prior ?? { previousExists: current.exists, previousValue: current.value };
383
+ setAt(object, keyPath, value);
384
+ context.next[key] = { type, path: op.path, keyPath, previousExists: original.previousExists, previousValue: original.previousValue, appliedHash: fingerprint({ exists: true, value }) };
385
+ touched.add(key);
386
+ }
387
+ await writeText(projectRoot, op.path, type === 'json' ? `${JSON.stringify(object, null, 2)}\n` : stringifyYaml(object));
388
+ }
389
+ }
390
+
391
+ async function reconcile(kind, { projectRoot, payloadRoot, manifest: inputManifest, executor }) {
392
+ const manifest = validateRemoteManifest(inputManifest);
393
+ const installedState = await readInstalledState(projectRoot);
394
+ const runtimeState = await readRuntimeState(projectRoot);
395
+ const installed = installedState.installed[manifest.id];
396
+ if (kind === 'install' && installed) throw new Error(`${manifest.id} is already installed`);
397
+ if (kind !== 'install' && !installed) throw new Error(`${manifest.id} is not installed`);
398
+ const prior = clone(runtimeState.ownership[manifest.id] ?? {});
399
+ const context = { projectRoot, payloadRoot, executor, prior, next: clone(prior) };
400
+
401
+ await runPhase(manifest, `pre_${kind}`, context);
402
+ const touched = new Set();
403
+ if (kind === 'remove') {
404
+ for (const [key, record] of Object.entries(prior)) { await restoreRecord(projectRoot, record); delete context.next[key]; }
405
+ } else {
406
+ for (const op of manifest.operations) if (!op.type.startsWith('run_')) await applyOperation(op, context, touched);
407
+ for (const [key, record] of Object.entries(prior)) {
408
+ if (!touched.has(key) && context.next[key]) { await restoreRecord(projectRoot, record); delete context.next[key]; }
409
+ }
410
+ }
411
+ await runPhase(manifest, `post_${kind}`, context);
412
+
413
+ if (kind === 'remove') {
414
+ delete installedState.installed[manifest.id];
415
+ installedState.requested = installedState.requested.filter((id) => id !== manifest.id);
416
+ delete runtimeState.ownership[manifest.id];
417
+ delete runtimeState.results[manifest.id];
418
+ } else {
419
+ const contentHash = String(manifest.contentHash ?? hash({ id: manifest.id, revision: manifest.revision ?? null, operations: manifest.operations, check: manifest.check ?? null }));
420
+ const revision = String(manifest.revision ?? contentHash);
421
+ installedState.installed[manifest.id] = {
422
+ kind: manifest.kind ?? 'rule',
423
+ version: String(manifest.version ?? contentHash),
424
+ revision,
425
+ contentHash,
426
+ ...(manifest.check ? { check: clone(manifest.check) } : {}),
427
+ };
428
+ installedState.requested = [...new Set([...installedState.requested, manifest.id])].sort();
429
+ runtimeState.ownership[manifest.id] = context.next;
430
+ }
431
+ installedState.schemaVersion = 2;
432
+ runtimeState.schemaVersion = 2;
433
+ await writeJsonState(projectRoot, INSTALLED_PATH, installedState);
434
+ await writeJsonState(projectRoot, STATE_PATH, runtimeState);
435
+ return installedState.installed[manifest.id] ?? null;
436
+ }
437
+
438
+ export async function installRule(options) { return reconcile('install', options); }
439
+ export async function syncRule(options) { return reconcile('sync', options); }
440
+ export async function removeRule(options) { return reconcile('remove', options); }
441
+
442
+ export async function runRemoteChecks(projectRoot, options = {}) {
443
+ const installedState = await readInstalledState(projectRoot);
444
+ const runtimeState = await readRuntimeState(projectRoot);
445
+ const executor = options.executor ?? ((command, args, runOptions) => new Promise((resolveRun, reject) => {
446
+ const child = spawn(command, args, { cwd: runOptions.cwd, stdio: 'inherit', shell: false });
447
+ child.on('error', reject);
448
+ child.on('close', (code) => resolveRun(code ?? 1));
449
+ }));
450
+ let exitCode = 0;
451
+ for (const [id, entry] of Object.entries(installedState.installed).sort(([a], [b]) => a.localeCompare(b))) {
452
+ if (!Array.isArray(entry.check?.command) || entry.check.command.length === 0) continue;
453
+ const [command, ...args] = entry.check.command;
454
+ const code = await executor(command, args, { cwd: projectRoot });
455
+ runtimeState.results[id] = { status: code === 0 ? 'pass' : 'fail', exitCode: code };
456
+ if (code !== 0) exitCode = 1;
457
+ }
458
+ runtimeState.schemaVersion = 2;
459
+ runtimeState.checkedAt = new Date(options.nowMs ?? Date.now()).toISOString();
460
+ await writeJsonState(projectRoot, STATE_PATH, runtimeState);
461
+ return { exitCode, results: runtimeState.results };
462
+ }
package/src/sync-core.js CHANGED
@@ -11,12 +11,14 @@ import {
11
11
  } from './shared-file.js';
12
12
 
13
13
  export const STATE_SCHEMA_VERSION = 2;
14
- export const CHECKS_SCHEMA_VERSION = 1;
14
+ export const CHECKS_SCHEMA_VERSION = 2;
15
15
  export const INSTALLED_RELATIVE_PATH = '.specdest/installed.json';
16
- export const CHECKS_RELATIVE_PATH = '.specdest/checks.json';
16
+ export const STATE_RELATIVE_PATH = '.specdest/state.json';
17
+ export const CHECKS_RELATIVE_PATH = STATE_RELATIVE_PATH;
18
+ export const LEGACY_CHECKS_RELATIVE_PATH = '.specdest/checks.json';
17
19
 
18
20
  const EMPTY_INSTALLED = Object.freeze({ schemaVersion: 2, requested: [], installed: {} });
19
- const EMPTY_CHECKS = Object.freeze({ schemaVersion: CHECKS_SCHEMA_VERSION, checkedAt: null, results: {} });
21
+ const EMPTY_CHECKS = Object.freeze({ schemaVersion: CHECKS_SCHEMA_VERSION, results: {} });
20
22
 
21
23
  function clone(value) {
22
24
  return JSON.parse(JSON.stringify(value));
@@ -51,11 +53,13 @@ function validateInstalledState(state) {
51
53
  }
52
54
 
53
55
  function validateChecksState(state) {
54
- if (state?.schemaVersion !== CHECKS_SCHEMA_VERSION || !state.results || Array.isArray(state.results) || typeof state.results !== 'object') {
55
- throw new Error('Invalid .specdest/checks.json state');
56
+ const legacy = state?.schemaVersion === 1;
57
+ const current = state?.schemaVersion === CHECKS_SCHEMA_VERSION;
58
+ if ((!legacy && !current) || !state.results || Array.isArray(state.results) || typeof state.results !== 'object') {
59
+ throw new Error('Invalid .specdest/state.json state');
56
60
  }
57
- if (state.checkedAt !== null && typeof state.checkedAt !== 'string') {
58
- throw new Error('Invalid .specdest/checks.json checkedAt');
61
+ if (legacy && state.checkedAt !== null && typeof state.checkedAt !== 'string') {
62
+ throw new Error('Invalid .specdest/state.json checkedAt');
59
63
  }
60
64
  return state;
61
65
  }
@@ -84,17 +88,29 @@ export async function writeInstalledState(projectRoot, state) {
84
88
  }
85
89
 
86
90
  export async function readChecksState(projectRoot) {
87
- const state = await readJsonOrDefault(join(projectRoot, CHECKS_RELATIVE_PATH), EMPTY_CHECKS);
91
+ const statePath = join(projectRoot, STATE_RELATIVE_PATH);
92
+ let state;
93
+ try {
94
+ state = JSON.parse(await readFile(statePath, 'utf8'));
95
+ } catch (error) {
96
+ if (error?.code !== 'ENOENT') throw error;
97
+ state = await readJsonOrDefault(join(projectRoot, LEGACY_CHECKS_RELATIVE_PATH), EMPTY_CHECKS);
98
+ }
88
99
  return validateChecksState(state);
89
100
  }
90
101
 
91
102
  export async function writeChecksState(projectRoot, state) {
92
103
  validateChecksState(state);
93
- await writeJsonAtomic(join(projectRoot, CHECKS_RELATIVE_PATH), state);
104
+ if (state.schemaVersion !== CHECKS_SCHEMA_VERSION) throw new Error('Cannot write legacy .specdest/state.json state');
105
+ const current = await readJsonOrDefault(join(projectRoot, STATE_RELATIVE_PATH), { schemaVersion: CHECKS_SCHEMA_VERSION });
106
+ await writeJsonAtomic(join(projectRoot, STATE_RELATIVE_PATH), { ...current, ...state, schemaVersion: CHECKS_SCHEMA_VERSION });
94
107
  }
95
108
 
96
109
  function validId(value) {
97
- return Boolean(value && value === value.toLowerCase() && value.split('-').every((part) => part && /^[a-z0-9_]+$/.test(part)));
110
+ return Boolean(
111
+ value &&
112
+ value.split('-').every((part) => part && /^[A-Za-z0-9_]+$/u.test(part)),
113
+ );
98
114
  }
99
115
 
100
116
  export function validateManifest(manifest) {
package/catalog/README.md DELETED
@@ -1,11 +0,0 @@
1
- # Devkit catalog
2
-
3
- Canonical machine-readable rule/module definitions shipped with `@specdest/devkit`.
4
-
5
- - `rules/<id>/manifest.json` declares rule-owned artifacts, dependencies, and checker command.
6
- - `modules/<id>/manifest.json` declares reusable infrastructure modules.
7
- - `source` fields are package-relative catalog files hydrated into artifact `content` before install/sync.
8
- - Rule skills install under `.agents/skills/<rule-id>/` and add only their owned `AGENTS.md` section.
9
- - `checker-runtime` owns shared checker helpers and the `.specdest/checks.json` gitignore entry.
10
-
11
- Stack-specific differences are not expressed through inheritance here; explicit stack modules are added separately.
@@ -1,14 +0,0 @@
1
- {
2
- "id": "backend-convex",
3
- "kind": "module",
4
- "version": "1.0.0",
5
- "requires": [
6
- "abac-permissions-convex",
7
- "convex-multi-presentation",
8
- "layers-and-contracts-convex",
9
- "module-size-rules-convex",
10
- "unit-test-rules-convex"
11
- ],
12
- "artifacts": [],
13
- "obsolete": []
14
- }
@@ -1,11 +0,0 @@
1
- {
2
- "id": "backend-convex-expo",
3
- "kind": "module",
4
- "version": "1.0.0",
5
- "requires": [
6
- "abac-permissions-convex",
7
- "module-size-rules-convex"
8
- ],
9
- "artifacts": [],
10
- "obsolete": []
11
- }
@@ -1,15 +0,0 @@
1
- {
2
- "id": "backend-supabase",
3
- "kind": "module",
4
- "version": "1.0.0",
5
- "requires": [
6
- "abac-permissions-supabase",
7
- "layers-and-contracts-supabase",
8
- "module-size-rules-supabase",
9
- "supabase-contracts",
10
- "supabase-declarative-schema",
11
- "unit-test-rules-supabase"
12
- ],
13
- "artifacts": [],
14
- "obsolete": []
15
- }
@@ -1,11 +0,0 @@
1
- {
2
- "id": "backend-supabase-expo",
3
- "kind": "module",
4
- "version": "1.0.0",
5
- "requires": [
6
- "abac-permissions-supabase",
7
- "module-size-rules-supabase"
8
- ],
9
- "artifacts": [],
10
- "obsolete": []
11
- }
@@ -1,25 +0,0 @@
1
- import { runtime } from "./runtime.ts";
2
- // fallow-ignore-next-line complexity
3
- function configPathFromArgs(args: string[], defaultUrl: URL): string | URL {
4
- const configArgIndex = args.indexOf("--config");
5
- const configPath = configArgIndex >= 0 ? args[configArgIndex + 1] : null;
6
- if (configArgIndex >= 0 && !configPath) {
7
- throw new Error("--config requires a path");
8
- }
9
- return configPath ?? defaultUrl;
10
- }
11
-
12
- async function readConfig<T>(args: string[], defaultUrl: URL): Promise<T> {
13
- return JSON.parse(await runtime.readTextFile(configPathFromArgs(args, defaultUrl))) as T;
14
- }
15
-
16
- export async function readSkillConfig<T>(moduleUrl: string): Promise<{ config: T; root: string }> {
17
- return {
18
- config: await readConfig<T>(runtime.args, new URL("./config.json", moduleUrl)),
19
- root: runtime.cwd(),
20
- };
21
- }
22
-
23
- export function assertSchemaVersion(version: number): void {
24
- if (version !== 1) throw new Error("config.json schemaVersion must be 1");
25
- }
@@ -1,48 +0,0 @@
1
- import { runtime } from "./runtime.ts";
2
- export function normalizePath(value: string): string {
3
- return value.replaceAll("\\", "/").replace(/^\.\//, "");
4
- }
5
-
6
- function isIgnoredDirectory(relativePath: string, ignoredDirectories: Set<string>): boolean {
7
- const normalized = normalizePath(relativePath);
8
- if (!normalized) return false;
9
- return ignoredDirectories.has(normalized) || ignoredDirectories.has(normalized.split("/")[0]);
10
- }
11
-
12
- export async function exists(path: string): Promise<boolean> {
13
- try {
14
- await runtime.stat(path);
15
- return true;
16
- } catch (error) {
17
- if (error instanceof runtime.errors.NotFound) return false;
18
- throw error;
19
- }
20
- }
21
-
22
- // fallow-ignore-next-line complexity
23
- export async function walk(
24
- directory: string,
25
- options: { ignoredDirectories?: Set<string>; relativeDirectory?: string } = {},
26
- ): Promise<string[]> {
27
- const { ignoredDirectories = new Set<string>(), relativeDirectory = "" } = options;
28
- if (isIgnoredDirectory(relativeDirectory, ignoredDirectories) || !(await exists(directory)))
29
- return [];
30
- const entries: string[] = [];
31
- for await (const entry of runtime.readDir(directory)) {
32
- const relativePath = normalizePath(
33
- relativeDirectory ? `${relativeDirectory}/${entry.name}` : entry.name,
34
- );
35
- const absolutePath = `${directory}/${entry.name}`;
36
- if (entry.isDirectory) {
37
- entries.push(
38
- ...(await walk(absolutePath, {
39
- ignoredDirectories,
40
- relativeDirectory: relativePath,
41
- })),
42
- );
43
- continue;
44
- }
45
- if (entry.isFile) entries.push(relativePath);
46
- }
47
- return entries;
48
- }