@specdest/devkit 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -18
- package/package.json +4 -4
- package/src/canonical-project-operations.js +164 -0
- package/src/canonical-project.js +78 -0
- package/src/canonical-source.js +114 -0
- package/src/cli.js +2 -2
- package/src/git-catalog.js +105 -0
- package/src/index.js +6 -2
- package/src/project-operations.js +65 -6
- package/src/remote-installer.js +478 -0
- package/src/sync-core.js +20 -7
- package/catalog/README.md +0 -11
- package/catalog/modules/backend-convex/manifest.json +0 -14
- package/catalog/modules/backend-convex-expo/manifest.json +0 -11
- package/catalog/modules/backend-supabase/manifest.json +0 -15
- package/catalog/modules/backend-supabase-expo/manifest.json +0 -11
- package/catalog/modules/checker-runtime/config.ts +0 -25
- package/catalog/modules/checker-runtime/fs.ts +0 -48
- package/catalog/modules/checker-runtime/manifest.json +0 -29
- package/catalog/modules/checker-runtime/runtime.ts +0 -79
- package/catalog/modules/devflow/.agents/skills/devflow/SKILL.md +0 -33
- package/catalog/modules/devflow/.devflow.json +0 -10
- package/catalog/modules/devflow/manifest.json +0 -35
- package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/SKILL.md +0 -85
- package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/activeScenario.mjs +0 -130
- package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/checkLocalEnvironment.mjs +0 -7
- package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/completeActiveScenario.mjs +0 -36
- package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/createActiveScenario.mjs +0 -143
- package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/localEnvironment.mjs +0 -43
- package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/prompt.mjs +0 -25
- package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/runActiveScenario.mjs +0 -66
- package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/runAuthoringScenario.mjs +0 -146
- package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/seed.mjs +0 -56
- package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/seedActiveScenario.mjs +0 -6
- package/catalog/modules/e2e-playwright/docs/e2e-playwright/README.md +0 -103
- package/catalog/modules/e2e-playwright/manifest.json +0 -206
- package/catalog/modules/e2e-playwright/playwright.e2e.config.ts +0 -39
- package/catalog/modules/e2e-playwright/tests/e2e/support/e2ePlaywrightFlow.ts +0 -107
- package/catalog/modules/e2e-playwright/tests/e2e/support/fixtures.ts +0 -27
- package/catalog/modules/local-log/AGENTS.local-log.md +0 -13
- package/catalog/modules/local-log/docs/features/local-logging/README.md +0 -70
- package/catalog/modules/local-log/manifest.json +0 -39
- package/catalog/modules/local-log/tmp/logs/.gitignore +0 -2
- package/catalog/modules/local-log/tools/local-log/README.md +0 -47
- package/catalog/modules/local-log/tools/local-log/local-log.mjs +0 -241
- package/catalog/modules/stack-common-vite/manifest.json +0 -16
- package/catalog/modules/stack-expo-convex/manifest.json +0 -31
- package/catalog/modules/stack-expo-supabase/manifest.json +0 -44
- package/catalog/modules/stack-vite-convex/manifest.json +0 -32
- package/catalog/modules/stack-vite-supabase/manifest.json +0 -45
- package/catalog/rules/abac-permissions-convex/SKILL.md +0 -17
- package/catalog/rules/abac-permissions-convex/check.ts +0 -87
- package/catalog/rules/abac-permissions-convex/manifest.json +0 -33
- package/catalog/rules/abac-permissions-supabase/SKILL.md +0 -17
- package/catalog/rules/abac-permissions-supabase/check.ts +0 -87
- package/catalog/rules/abac-permissions-supabase/manifest.json +0 -33
- package/catalog/rules/convex-multi-presentation/SKILL.md +0 -47
- package/catalog/rules/convex-multi-presentation/check.ts +0 -205
- package/catalog/rules/convex-multi-presentation/manifest.json +0 -47
- package/catalog/rules/convex-multi-presentation/policy.ts +0 -261
- package/catalog/rules/design-rules/SKILL.md +0 -12
- package/catalog/rules/design-rules/check.ts +0 -84
- package/catalog/rules/design-rules/config.json +0 -5
- package/catalog/rules/design-rules/manifest.json +0 -38
- package/catalog/rules/e2e-test-rules/SKILL.md +0 -46
- package/catalog/rules/e2e-test-rules/check.ts +0 -145
- package/catalog/rules/e2e-test-rules/config.json +0 -32
- package/catalog/rules/e2e-test-rules/manifest.json +0 -38
- package/catalog/rules/error-handling-rules/SKILL.md +0 -21
- package/catalog/rules/error-handling-rules/check.ts +0 -73
- package/catalog/rules/error-handling-rules/manifest.json +0 -33
- package/catalog/rules/layers-and-contracts/SKILL.md +0 -36
- package/catalog/rules/layers-and-contracts/check.ts +0 -266
- package/catalog/rules/layers-and-contracts/manifest.json +0 -33
- package/catalog/rules/layers-and-contracts-convex/SKILL.md +0 -49
- package/catalog/rules/layers-and-contracts-convex/check.ts +0 -289
- package/catalog/rules/layers-and-contracts-convex/manifest.json +0 -38
- package/catalog/rules/layers-and-contracts-convex/policy.ts +0 -68
- package/catalog/rules/layers-and-contracts-supabase/SKILL.md +0 -52
- package/catalog/rules/layers-and-contracts-supabase/check.ts +0 -371
- package/catalog/rules/layers-and-contracts-supabase/manifest.json +0 -38
- package/catalog/rules/layers-and-contracts-supabase/policy.ts +0 -68
- package/catalog/rules/module-size-rules/SKILL.md +0 -5
- package/catalog/rules/module-size-rules/check.ts +0 -144
- package/catalog/rules/module-size-rules/config.json +0 -6
- package/catalog/rules/module-size-rules/manifest.json +0 -38
- package/catalog/rules/module-size-rules-convex/SKILL.md +0 -5
- package/catalog/rules/module-size-rules-convex/check.ts +0 -146
- package/catalog/rules/module-size-rules-convex/config.json +0 -6
- package/catalog/rules/module-size-rules-convex/manifest.json +0 -38
- package/catalog/rules/module-size-rules-supabase/SKILL.md +0 -5
- package/catalog/rules/module-size-rules-supabase/check.ts +0 -146
- package/catalog/rules/module-size-rules-supabase/config.json +0 -12
- package/catalog/rules/module-size-rules-supabase/manifest.json +0 -38
- package/catalog/rules/mutation-command-rules/SKILL.md +0 -15
- package/catalog/rules/mutation-command-rules/check.ts +0 -30
- package/catalog/rules/mutation-command-rules/config.json +0 -19
- package/catalog/rules/mutation-command-rules/manifest.json +0 -38
- package/catalog/rules/nearby-contracts/SKILL.md +0 -18
- package/catalog/rules/nearby-contracts/check.ts +0 -138
- package/catalog/rules/nearby-contracts/config.json +0 -10
- package/catalog/rules/nearby-contracts/manifest.json +0 -38
- package/catalog/rules/no-raw-click-buttons/SKILL.md +0 -5
- package/catalog/rules/no-raw-click-buttons/check.ts +0 -37
- package/catalog/rules/no-raw-click-buttons/manifest.json +0 -33
- package/catalog/rules/public-api-export-barrels/SKILL.md +0 -45
- package/catalog/rules/public-api-export-barrels/check.ts +0 -73
- package/catalog/rules/public-api-export-barrels/config.json +0 -4
- package/catalog/rules/public-api-export-barrels/manifest.json +0 -38
- package/catalog/rules/route-tree-fresh/SKILL.md +0 -16
- package/catalog/rules/route-tree-fresh/check.ts +0 -66
- package/catalog/rules/route-tree-fresh/manifest.json +0 -33
- package/catalog/rules/strict-typescript/SKILL.md +0 -3
- package/catalog/rules/strict-typescript/check.ts +0 -119
- package/catalog/rules/strict-typescript/manifest.json +0 -33
- package/catalog/rules/supabase-contracts/SKILL.md +0 -3
- package/catalog/rules/supabase-contracts/check.ts +0 -172
- package/catalog/rules/supabase-contracts/manifest.json +0 -33
- package/catalog/rules/supabase-declarative-schema/SKILL.md +0 -30
- package/catalog/rules/supabase-declarative-schema/check.ts +0 -262
- package/catalog/rules/supabase-declarative-schema/config.json +0 -8
- package/catalog/rules/supabase-declarative-schema/manifest.json +0 -38
- package/catalog/rules/tanstack-form-rules/SKILL.md +0 -11
- package/catalog/rules/tanstack-form-rules/check.ts +0 -58
- package/catalog/rules/tanstack-form-rules/manifest.json +0 -33
- package/catalog/rules/unit-test-rules/SKILL.md +0 -55
- package/catalog/rules/unit-test-rules/check.ts +0 -132
- package/catalog/rules/unit-test-rules/config.json +0 -22
- package/catalog/rules/unit-test-rules/manifest.json +0 -38
- package/catalog/rules/unit-test-rules-convex/SKILL.md +0 -41
- package/catalog/rules/unit-test-rules-convex/check.ts +0 -418
- package/catalog/rules/unit-test-rules-convex/manifest.json +0 -33
- package/catalog/rules/unit-test-rules-supabase/SKILL.md +0 -40
- package/catalog/rules/unit-test-rules-supabase/check.ts +0 -492
- package/catalog/rules/unit-test-rules-supabase/manifest.json +0 -33
- package/catalog/rules/workstation-controller-rules/SKILL.md +0 -22
- package/catalog/rules/workstation-controller-rules/check.ts +0 -108
- package/catalog/rules/workstation-controller-rules/manifest.json +0 -33
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
+
import { readdir } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
2
4
|
|
|
3
|
-
import { resolveCatalogSelection } from './catalog.js';
|
|
5
|
+
import { listCatalogEntries, loadCatalogEntry, resolveCatalogSelection } from './catalog.js';
|
|
4
6
|
import { evaluateSetupRequirements } from './setup-requirements.js';
|
|
5
7
|
import {
|
|
6
8
|
applySyncPlan,
|
|
@@ -24,6 +26,53 @@ function defaultExecutor({ command, args, cwd }) {
|
|
|
24
26
|
});
|
|
25
27
|
}
|
|
26
28
|
|
|
29
|
+
async function hydrateInstalledCheckMetadata(installed, options = {}) {
|
|
30
|
+
const catalogIds = new Set((await listCatalogEntries(options)).map((entry) => entry.id));
|
|
31
|
+
const hydrated = {};
|
|
32
|
+
for (const [id, entry] of Object.entries(installed)) {
|
|
33
|
+
if (entry.check || !catalogIds.has(id)) {
|
|
34
|
+
hydrated[id] = entry;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const catalogEntry = await loadCatalogEntry(id, options);
|
|
38
|
+
hydrated[id] = catalogEntry.check ? { ...entry, check: catalogEntry.check } : entry;
|
|
39
|
+
}
|
|
40
|
+
return hydrated;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function auditSkillOwnership(projectRoot, installed) {
|
|
44
|
+
const allowedDirectories = new Set();
|
|
45
|
+
if (installed['checker-runtime']) allowedDirectories.add('shared');
|
|
46
|
+
|
|
47
|
+
for (const [id, entry] of Object.entries(installed)) {
|
|
48
|
+
allowedDirectories.add(id);
|
|
49
|
+
for (const suffix of ['-supabase', '-convex', '-expo']) {
|
|
50
|
+
if (id.endsWith(suffix)) allowedDirectories.add(id.slice(0, -suffix.length));
|
|
51
|
+
}
|
|
52
|
+
for (const value of entry.check?.command ?? []) {
|
|
53
|
+
const match = String(value).match(/^\.agents\/skills\/([^/]+)\//u);
|
|
54
|
+
if (match?.[1]) allowedDirectories.add(match[1]);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let entries;
|
|
59
|
+
try {
|
|
60
|
+
entries = await readdir(join(projectRoot, '.agents', 'skills'), { withFileTypes: true });
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (error?.code === 'ENOENT') return { unownedSkillDirectories: [] };
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
const actualDirectories = entries
|
|
66
|
+
.filter((entry) => entry.isDirectory())
|
|
67
|
+
.map((entry) => entry.name)
|
|
68
|
+
.sort();
|
|
69
|
+
return {
|
|
70
|
+
unownedSkillDirectories: actualDirectories.filter(
|
|
71
|
+
(directory) => !allowedDirectories.has(directory),
|
|
72
|
+
),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
27
76
|
export async function installCatalogEntry(projectRoot, id, options = {}) {
|
|
28
77
|
const current = await readInstalledState(projectRoot);
|
|
29
78
|
const currentEntries = await resolveCatalogSelection(Object.keys(current.installed), options);
|
|
@@ -63,18 +112,22 @@ export async function getProjectStatus(projectRoot, options = {}) {
|
|
|
63
112
|
|
|
64
113
|
export async function runInstalledChecks(projectRoot, options = {}) {
|
|
65
114
|
const current = await readInstalledState(projectRoot);
|
|
66
|
-
const
|
|
115
|
+
const installed = await hydrateInstalledCheckMetadata(current.installed, options);
|
|
67
116
|
const executor = options.executor ?? defaultExecutor;
|
|
68
117
|
const results = {};
|
|
69
|
-
|
|
118
|
+
const integrity = await auditSkillOwnership(projectRoot, installed);
|
|
119
|
+
let exitCode = integrity.unownedSkillDirectories.length ? 1 : 0;
|
|
70
120
|
|
|
71
|
-
|
|
121
|
+
const installedEntries = Object.entries(installed).sort(([left], [right]) =>
|
|
122
|
+
left.localeCompare(right),
|
|
123
|
+
);
|
|
124
|
+
for (const [id, entry] of installedEntries) {
|
|
72
125
|
if (entry.kind !== 'rule' || !entry.check) continue;
|
|
73
126
|
const [command, ...args] = entry.check.command;
|
|
74
127
|
const execution = await executor({ command, args, cwd: projectRoot });
|
|
75
128
|
const status = execution.exitCode === 0 ? 'pass' : 'fail';
|
|
76
129
|
if (execution.exitCode !== 0) exitCode = 1;
|
|
77
|
-
results[
|
|
130
|
+
results[id] = {
|
|
78
131
|
status,
|
|
79
132
|
exitCode: execution.exitCode,
|
|
80
133
|
stdout: execution.stdout ?? '',
|
|
@@ -86,7 +139,7 @@ export async function runInstalledChecks(projectRoot, options = {}) {
|
|
|
86
139
|
Object.entries(results).map(([id, result]) => [id, { status: result.status }]),
|
|
87
140
|
);
|
|
88
141
|
await writeChecksState(projectRoot, { schemaVersion: 2, results: persistedResults });
|
|
89
|
-
return { exitCode, results };
|
|
142
|
+
return { exitCode, results, integrity };
|
|
90
143
|
}
|
|
91
144
|
|
|
92
145
|
export function createProjectCommandHandlers(projectRoot = process.cwd()) {
|
|
@@ -124,6 +177,12 @@ export function createProjectCommandHandlers(projectRoot = process.cwd()) {
|
|
|
124
177
|
}
|
|
125
178
|
const result = await runInstalledChecks(projectRoot);
|
|
126
179
|
for (const [id, check] of Object.entries(result.results)) io.stdout.write(`${check.status.toUpperCase()} ${id}\n`);
|
|
180
|
+
if (result.integrity.unownedSkillDirectories.length) {
|
|
181
|
+
io.stderr.write('FAIL devkit-skill-ownership: unowned directories found under .agents/skills; move project-only enforcement to .agents/project-skills\n');
|
|
182
|
+
for (const directory of result.integrity.unownedSkillDirectories) {
|
|
183
|
+
io.stderr.write(`- .agents/skills/${directory}\n`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
127
186
|
return result.exitCode;
|
|
128
187
|
},
|
|
129
188
|
};
|
|
@@ -0,0 +1,478 @@
|
|
|
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', 'scaffold_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.mode === 'scaffold' || copy.mode === 'create-only' ? 'scaffold_file' : '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 === 'scaffold_file') {
|
|
328
|
+
const target = resolveProjectPath(projectRoot, op.path);
|
|
329
|
+
const key = ownershipKey('file', op.path);
|
|
330
|
+
const prior = context.prior[key];
|
|
331
|
+
if (prior) {
|
|
332
|
+
// Reclassifying a formerly managed file as a scaffold intentionally hands
|
|
333
|
+
// ownership to the project. Preserve whatever the project currently has.
|
|
334
|
+
delete context.next[key];
|
|
335
|
+
touched.add(key);
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
if (!(await exists(target))) {
|
|
339
|
+
await writeText(projectRoot, op.path, await readFile(payloadPath(payloadRoot, op.source), 'utf8'));
|
|
340
|
+
}
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
if (op.type === 'copy_directory') {
|
|
344
|
+
const sourceRoot = payloadPath(payloadRoot, op.source);
|
|
345
|
+
const walk = async (dir, prefix = '') => {
|
|
346
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
347
|
+
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
348
|
+
if (entry.isDirectory()) await walk(resolve(dir, entry.name), relative);
|
|
349
|
+
else if (entry.isFile()) await claimFile(context, resolve(dir, entry.name), `${op.path.replace(/\/$/u, '')}/${relative}`, touched);
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
return walk(sourceRoot);
|
|
353
|
+
}
|
|
354
|
+
if (op.type === 'delete_owned_artifact') {
|
|
355
|
+
const matches = Object.entries(context.next).filter(([, record]) => record.path === op.path && record.type === 'file');
|
|
356
|
+
if (!matches.length) throw new Error(`Artifact is not owned: ${op.path}`);
|
|
357
|
+
for (const [key, record] of matches) { await restoreRecord(projectRoot, record, { deleteInstead: true }); delete context.next[key]; touched.add(key); }
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
if (op.type === 'managed_section') {
|
|
361
|
+
const key = ownershipKey('markdown', op.path, op.heading);
|
|
362
|
+
const prior = context.prior[key];
|
|
363
|
+
const text = await readText(projectRoot, op.path);
|
|
364
|
+
const current = markdownSection(text, op.heading);
|
|
365
|
+
if (prior) assertFingerprint(prior, current, op.path);
|
|
366
|
+
const original = prior ?? { previousExists: current.exists, previousValue: current.value };
|
|
367
|
+
const updated = upsertMarkdownSection(text, op.heading, op.content ?? '');
|
|
368
|
+
await writeText(projectRoot, op.path, updated);
|
|
369
|
+
const applied = markdownSection(updated, op.heading);
|
|
370
|
+
context.next[key] = { type: 'markdown', path: op.path, heading: op.heading, previousExists: original.previousExists, previousValue: original.previousValue, appliedHash: fingerprint(applied) };
|
|
371
|
+
touched.add(key); return;
|
|
372
|
+
}
|
|
373
|
+
if (op.type === 'env_set' || op.type === 'env_remove') {
|
|
374
|
+
const key = ownershipKey('env', op.path, op.key);
|
|
375
|
+
const prior = context.prior[key];
|
|
376
|
+
let text = await readText(projectRoot, op.path);
|
|
377
|
+
const map = envMap(text);
|
|
378
|
+
const current = { exists: map.has(op.key), value: map.get(op.key) };
|
|
379
|
+
if (prior) assertFingerprint(prior, current, op.path);
|
|
380
|
+
const original = prior ?? { previousExists: current.exists, previousValue: current.value };
|
|
381
|
+
text = op.type === 'env_set' ? setEnv(text, op.key, String(op.value ?? '')) : removeEnv(text, op.key);
|
|
382
|
+
await writeText(projectRoot, op.path, text);
|
|
383
|
+
const updatedMap = envMap(text);
|
|
384
|
+
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) }) };
|
|
385
|
+
touched.add(key); return;
|
|
386
|
+
}
|
|
387
|
+
if (['json_set', 'json_merge', 'yaml_set', 'yaml_merge'].includes(op.type)) {
|
|
388
|
+
const type = op.type.startsWith('json') ? 'json' : 'yaml';
|
|
389
|
+
const text = await readText(projectRoot, op.path);
|
|
390
|
+
const object = type === 'json' ? (text.trim() ? JSON.parse(text) : {}) : parseYaml(text);
|
|
391
|
+
const assignments = op.type.endsWith('_set') ? [[op.keyPath, op.value]] : leaves(op.value);
|
|
392
|
+
for (const [keyPath, value] of assignments) {
|
|
393
|
+
if (!Array.isArray(keyPath) || !keyPath.length) throw new Error(`Structured operation requires keyPath/value leaves: ${op.path}`);
|
|
394
|
+
const key = ownershipKey(type, op.path, keyPath.join('.'));
|
|
395
|
+
const prior = context.prior[key];
|
|
396
|
+
const current = getAt(object, keyPath);
|
|
397
|
+
if (prior) assertFingerprint(prior, current, op.path);
|
|
398
|
+
const original = prior ?? { previousExists: current.exists, previousValue: current.value };
|
|
399
|
+
setAt(object, keyPath, value);
|
|
400
|
+
context.next[key] = { type, path: op.path, keyPath, previousExists: original.previousExists, previousValue: original.previousValue, appliedHash: fingerprint({ exists: true, value }) };
|
|
401
|
+
touched.add(key);
|
|
402
|
+
}
|
|
403
|
+
await writeText(projectRoot, op.path, type === 'json' ? `${JSON.stringify(object, null, 2)}\n` : stringifyYaml(object));
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async function reconcile(kind, { projectRoot, payloadRoot, manifest: inputManifest, executor }) {
|
|
408
|
+
const manifest = validateRemoteManifest(inputManifest);
|
|
409
|
+
const installedState = await readInstalledState(projectRoot);
|
|
410
|
+
const runtimeState = await readRuntimeState(projectRoot);
|
|
411
|
+
const installed = installedState.installed[manifest.id];
|
|
412
|
+
if (kind === 'install' && installed) throw new Error(`${manifest.id} is already installed`);
|
|
413
|
+
if (kind !== 'install' && !installed) throw new Error(`${manifest.id} is not installed`);
|
|
414
|
+
const prior = clone(runtimeState.ownership[manifest.id] ?? {});
|
|
415
|
+
const context = { projectRoot, payloadRoot, executor, prior, next: clone(prior) };
|
|
416
|
+
|
|
417
|
+
await runPhase(manifest, `pre_${kind}`, context);
|
|
418
|
+
const touched = new Set();
|
|
419
|
+
if (kind === 'remove') {
|
|
420
|
+
for (const [key, record] of Object.entries(prior)) { await restoreRecord(projectRoot, record); delete context.next[key]; }
|
|
421
|
+
} else {
|
|
422
|
+
for (const op of manifest.operations) if (!op.type.startsWith('run_')) await applyOperation(op, context, touched);
|
|
423
|
+
for (const [key, record] of Object.entries(prior)) {
|
|
424
|
+
if (!touched.has(key) && context.next[key]) { await restoreRecord(projectRoot, record); delete context.next[key]; }
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
await runPhase(manifest, `post_${kind}`, context);
|
|
428
|
+
|
|
429
|
+
if (kind === 'remove') {
|
|
430
|
+
delete installedState.installed[manifest.id];
|
|
431
|
+
installedState.requested = installedState.requested.filter((id) => id !== manifest.id);
|
|
432
|
+
delete runtimeState.ownership[manifest.id];
|
|
433
|
+
delete runtimeState.results[manifest.id];
|
|
434
|
+
} else {
|
|
435
|
+
const contentHash = String(manifest.contentHash ?? hash({ id: manifest.id, revision: manifest.revision ?? null, operations: manifest.operations, check: manifest.check ?? null }));
|
|
436
|
+
const revision = String(manifest.revision ?? contentHash);
|
|
437
|
+
installedState.installed[manifest.id] = {
|
|
438
|
+
kind: manifest.kind ?? 'rule',
|
|
439
|
+
version: String(manifest.version ?? contentHash),
|
|
440
|
+
revision,
|
|
441
|
+
contentHash,
|
|
442
|
+
...(manifest.check ? { check: clone(manifest.check) } : {}),
|
|
443
|
+
};
|
|
444
|
+
installedState.requested = [...new Set([...installedState.requested, manifest.id])].sort();
|
|
445
|
+
runtimeState.ownership[manifest.id] = context.next;
|
|
446
|
+
}
|
|
447
|
+
installedState.schemaVersion = 2;
|
|
448
|
+
runtimeState.schemaVersion = 2;
|
|
449
|
+
await writeJsonState(projectRoot, INSTALLED_PATH, installedState);
|
|
450
|
+
await writeJsonState(projectRoot, STATE_PATH, runtimeState);
|
|
451
|
+
return installedState.installed[manifest.id] ?? null;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export async function installRule(options) { return reconcile('install', options); }
|
|
455
|
+
export async function syncRule(options) { return reconcile('sync', options); }
|
|
456
|
+
export async function removeRule(options) { return reconcile('remove', options); }
|
|
457
|
+
|
|
458
|
+
export async function runRemoteChecks(projectRoot, options = {}) {
|
|
459
|
+
const installedState = await readInstalledState(projectRoot);
|
|
460
|
+
const runtimeState = await readRuntimeState(projectRoot);
|
|
461
|
+
const executor = options.executor ?? ((command, args, runOptions) => new Promise((resolveRun, reject) => {
|
|
462
|
+
const child = spawn(command, args, { cwd: runOptions.cwd, stdio: 'inherit', shell: false });
|
|
463
|
+
child.on('error', reject);
|
|
464
|
+
child.on('close', (code) => resolveRun(code ?? 1));
|
|
465
|
+
}));
|
|
466
|
+
let exitCode = 0;
|
|
467
|
+
for (const [id, entry] of Object.entries(installedState.installed).sort(([a], [b]) => a.localeCompare(b))) {
|
|
468
|
+
if (!Array.isArray(entry.check?.command) || entry.check.command.length === 0) continue;
|
|
469
|
+
const [command, ...args] = entry.check.command;
|
|
470
|
+
const code = await executor(command, args, { cwd: projectRoot });
|
|
471
|
+
runtimeState.results[id] = { status: code === 0 ? 'pass' : 'fail', exitCode: code };
|
|
472
|
+
if (code !== 0) exitCode = 1;
|
|
473
|
+
}
|
|
474
|
+
runtimeState.schemaVersion = 2;
|
|
475
|
+
runtimeState.checkedAt = new Date(options.nowMs ?? Date.now()).toISOString();
|
|
476
|
+
await writeJsonState(projectRoot, STATE_PATH, runtimeState);
|
|
477
|
+
return { exitCode, results: runtimeState.results };
|
|
478
|
+
}
|
package/src/sync-core.js
CHANGED
|
@@ -13,7 +13,9 @@ import {
|
|
|
13
13
|
export const STATE_SCHEMA_VERSION = 2;
|
|
14
14
|
export const CHECKS_SCHEMA_VERSION = 2;
|
|
15
15
|
export const INSTALLED_RELATIVE_PATH = '.specdest/installed.json';
|
|
16
|
-
export const
|
|
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
21
|
const EMPTY_CHECKS = Object.freeze({ schemaVersion: CHECKS_SCHEMA_VERSION, results: {} });
|
|
@@ -54,10 +56,10 @@ function validateChecksState(state) {
|
|
|
54
56
|
const legacy = state?.schemaVersion === 1;
|
|
55
57
|
const current = state?.schemaVersion === CHECKS_SCHEMA_VERSION;
|
|
56
58
|
if ((!legacy && !current) || !state.results || Array.isArray(state.results) || typeof state.results !== 'object') {
|
|
57
|
-
throw new Error('Invalid .specdest/
|
|
59
|
+
throw new Error('Invalid .specdest/state.json state');
|
|
58
60
|
}
|
|
59
61
|
if (legacy && state.checkedAt !== null && typeof state.checkedAt !== 'string') {
|
|
60
|
-
throw new Error('Invalid .specdest/
|
|
62
|
+
throw new Error('Invalid .specdest/state.json checkedAt');
|
|
61
63
|
}
|
|
62
64
|
return state;
|
|
63
65
|
}
|
|
@@ -86,18 +88,29 @@ export async function writeInstalledState(projectRoot, state) {
|
|
|
86
88
|
}
|
|
87
89
|
|
|
88
90
|
export async function readChecksState(projectRoot) {
|
|
89
|
-
const
|
|
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
|
+
}
|
|
90
99
|
return validateChecksState(state);
|
|
91
100
|
}
|
|
92
101
|
|
|
93
102
|
export async function writeChecksState(projectRoot, state) {
|
|
94
103
|
validateChecksState(state);
|
|
95
|
-
if (state.schemaVersion !== CHECKS_SCHEMA_VERSION) throw new Error('Cannot write legacy .specdest/
|
|
96
|
-
await
|
|
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 });
|
|
97
107
|
}
|
|
98
108
|
|
|
99
109
|
function validId(value) {
|
|
100
|
-
return Boolean(
|
|
110
|
+
return Boolean(
|
|
111
|
+
value &&
|
|
112
|
+
value.split('-').every((part) => part && /^[A-Za-z0-9_]+$/u.test(part)),
|
|
113
|
+
);
|
|
101
114
|
}
|
|
102
115
|
|
|
103
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. `.specdest/checks.json` is committed project state and must not be ignored.
|
|
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
|
-
}
|