@specdest/devkit 0.4.6 → 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.
- package/README.md +34 -4
- package/dist/npm/canonical-project-operations.d.ts +5 -0
- package/dist/npm/canonical-project-operations.js +5 -0
- package/dist/npm/canonical-project.d.ts +10 -0
- package/dist/npm/canonical-project.js +109 -0
- package/dist/npm/canonical-source.d.ts +14 -0
- package/dist/npm/canonical-source.js +216 -0
- package/dist/npm/catalog-snapshot.d.ts +47 -0
- package/dist/npm/catalog-snapshot.js +28 -0
- package/dist/npm/cli.d.ts +2 -0
- package/dist/npm/cli.js +15 -0
- package/dist/npm/commands.d.ts +9 -0
- package/dist/npm/commands.js +157 -0
- package/dist/npm/flow.d.ts +48 -0
- package/dist/npm/flow.js +396 -0
- package/dist/npm/fuzz.d.ts +138 -0
- package/dist/npm/fuzz.js +327 -0
- package/dist/npm/git-catalog.d.ts +39 -0
- package/dist/npm/git-catalog.js +190 -0
- package/dist/npm/index.d.ts +5 -0
- package/dist/npm/index.js +22 -0
- package/dist/npm/installer-primitives.d.ts +3 -0
- package/dist/npm/installer-primitives.js +50 -0
- package/dist/npm/predefined-packages/abac.d.ts +2 -0
- package/dist/npm/predefined-packages/abac.js +22 -0
- package/dist/npm/predefined-packages/auth.d.ts +2 -0
- package/dist/npm/predefined-packages/auth.js +21 -0
- package/dist/npm/predefined-packages/convex.d.ts +2 -0
- package/dist/npm/predefined-packages/convex.js +53 -0
- package/dist/npm/predefined-packages/expo.d.ts +2 -0
- package/dist/npm/predefined-packages/expo.js +84 -0
- package/dist/npm/predefined-packages/firebase-hosting.d.ts +2 -0
- package/dist/npm/predefined-packages/firebase-hosting.js +24 -0
- package/dist/npm/predefined-packages/health.d.ts +10 -0
- package/dist/npm/predefined-packages/health.js +52 -0
- package/dist/npm/predefined-packages/husky.d.ts +2 -0
- package/dist/npm/predefined-packages/husky.js +57 -0
- package/dist/npm/predefined-packages/index.d.ts +11 -0
- package/dist/npm/predefined-packages/index.js +56 -0
- package/dist/npm/predefined-packages/install.d.ts +19 -0
- package/dist/npm/predefined-packages/install.js +85 -0
- package/dist/npm/predefined-packages/local-logging.d.ts +2 -0
- package/dist/npm/predefined-packages/local-logging.js +17 -0
- package/dist/npm/predefined-packages/logging.d.ts +2 -0
- package/dist/npm/predefined-packages/logging.js +21 -0
- package/dist/npm/predefined-packages/multi-tenancy.d.ts +2 -0
- package/dist/npm/predefined-packages/multi-tenancy.js +21 -0
- package/dist/npm/predefined-packages/nps.d.ts +2 -0
- package/dist/npm/predefined-packages/nps.js +32 -0
- package/dist/npm/predefined-packages/oxfmt.d.ts +2 -0
- package/dist/npm/predefined-packages/oxfmt.js +22 -0
- package/dist/npm/predefined-packages/oxlint.d.ts +2 -0
- package/dist/npm/predefined-packages/oxlint.js +35 -0
- package/dist/npm/predefined-packages/package-json.d.ts +3 -0
- package/dist/npm/predefined-packages/package-json.js +61 -0
- package/dist/npm/predefined-packages/payments.d.ts +2 -0
- package/dist/npm/predefined-packages/payments.js +31 -0
- package/dist/npm/predefined-packages/playwright.d.ts +2 -0
- package/dist/npm/predefined-packages/playwright.js +35 -0
- package/dist/npm/predefined-packages/project-signals.d.ts +4 -0
- package/dist/npm/predefined-packages/project-signals.js +39 -0
- package/dist/npm/predefined-packages/registry.d.ts +3 -0
- package/dist/npm/predefined-packages/registry.js +63 -0
- package/dist/npm/predefined-packages/resolver.d.ts +8 -0
- package/dist/npm/predefined-packages/resolver.js +35 -0
- package/dist/npm/predefined-packages/sentry.d.ts +2 -0
- package/dist/npm/predefined-packages/sentry.js +29 -0
- package/dist/npm/predefined-packages/shadcn.d.ts +2 -0
- package/dist/npm/predefined-packages/shadcn.js +23 -0
- package/dist/npm/predefined-packages/storybook.d.ts +2 -0
- package/dist/npm/predefined-packages/storybook.js +25 -0
- package/dist/npm/predefined-packages/stryker.d.ts +2 -0
- package/dist/npm/predefined-packages/stryker.js +48 -0
- package/dist/npm/predefined-packages/supabase.d.ts +2 -0
- package/dist/npm/predefined-packages/supabase.js +84 -0
- package/dist/npm/predefined-packages/tailwind.d.ts +2 -0
- package/dist/npm/predefined-packages/tailwind.js +18 -0
- package/dist/npm/predefined-packages/tanstack-form.d.ts +2 -0
- package/dist/npm/predefined-packages/tanstack-form.js +19 -0
- package/dist/npm/predefined-packages/tanstack-query.d.ts +2 -0
- package/dist/npm/predefined-packages/tanstack-query.js +15 -0
- package/dist/npm/predefined-packages/tanstack-router.d.ts +2 -0
- package/dist/npm/predefined-packages/tanstack-router.js +18 -0
- package/dist/npm/predefined-packages/types.d.ts +31 -0
- package/dist/npm/predefined-packages/types.js +1 -0
- package/dist/npm/predefined-packages/vite.d.ts +2 -0
- package/dist/npm/predefined-packages/vite.js +123 -0
- package/dist/npm/predefined-packages/vitest.d.ts +2 -0
- package/dist/npm/predefined-packages/vitest.js +20 -0
- package/dist/npm/predefined-packages/zod.d.ts +2 -0
- package/dist/npm/predefined-packages/zod.js +18 -0
- package/dist/npm/project-check.d.ts +6 -0
- package/dist/npm/project-check.js +87 -0
- package/dist/npm/project-context.d.ts +42 -0
- package/dist/npm/project-context.js +192 -0
- package/dist/npm/project-rules.d.ts +22 -0
- package/dist/npm/project-rules.js +66 -0
- package/dist/npm/project-runtime.d.ts +18 -0
- package/dist/npm/project-runtime.js +27 -0
- package/dist/npm/project-status.d.ts +32 -0
- package/dist/npm/project-status.js +56 -0
- package/dist/npm/project-sync.d.ts +7 -0
- package/dist/npm/project-sync.js +135 -0
- package/dist/npm/remote-installer.d.ts +4 -0
- package/dist/npm/remote-installer.js +312 -0
- package/dist/npm/state.d.ts +14 -0
- package/dist/npm/state.js +182 -0
- package/package.json +10 -7
- package/src/canonical-project-operations.js +0 -438
- package/src/canonical-project.js +0 -136
- package/src/canonical-source.js +0 -250
- package/src/catalog-snapshot.js +0 -39
- package/src/catalog.js +0 -117
- package/src/cli.js +0 -14
- package/src/fuzz.js +0 -291
- package/src/git-catalog.js +0 -177
- package/src/index.js +0 -36
- package/src/installer-primitives.js +0 -198
- package/src/project-operations.js +0 -189
- package/src/project-targeting.js +0 -48
- package/src/remote-installer.js +0 -479
- package/src/rule-profile.js +0 -61
- package/src/setup-requirements.js +0 -82
- package/src/shared-file.js +0 -131
- package/src/sync-core.js +0 -390
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { createCanonicalSource } from "./canonical-source.js";
|
|
2
|
+
import { canonicalCheck } from "./project-check.js";
|
|
3
|
+
import { aiInstructionText, canonicalRules } from "./project-rules.js";
|
|
4
|
+
import { canonicalDoctor, canonicalStatus } from "./project-status.js";
|
|
5
|
+
import { addPredefinedPackage } from "./predefined-packages/index.js";
|
|
6
|
+
import { canonicalSync } from "./project-sync.js";
|
|
7
|
+
function flags(args) {
|
|
8
|
+
const known = new Set(['--refresh', '--json']);
|
|
9
|
+
for (const arg of args)
|
|
10
|
+
if (!known.has(arg))
|
|
11
|
+
throw new Error(`Unknown option: ${arg}`);
|
|
12
|
+
return { refresh: args.includes('--refresh'), json: args.includes('--json') };
|
|
13
|
+
}
|
|
14
|
+
function checkFlags(args) {
|
|
15
|
+
const result = {
|
|
16
|
+
refresh: false,
|
|
17
|
+
mode: 'full',
|
|
18
|
+
files: null,
|
|
19
|
+
};
|
|
20
|
+
const remaining = [];
|
|
21
|
+
for (const arg of args) {
|
|
22
|
+
if (arg === '--refresh')
|
|
23
|
+
result.refresh = true;
|
|
24
|
+
else
|
|
25
|
+
remaining.push(arg);
|
|
26
|
+
}
|
|
27
|
+
if (remaining.includes('--staged') && remaining.includes('--files'))
|
|
28
|
+
throw new Error('Use either --staged or --files, not both');
|
|
29
|
+
if (remaining.includes('--staged')) {
|
|
30
|
+
if (remaining.length !== 1)
|
|
31
|
+
throw new Error('Usage: specdest check [--refresh] [--staged | --files <path...>]');
|
|
32
|
+
result.mode = 'staged';
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
const filesIndex = remaining.indexOf('--files');
|
|
36
|
+
if (filesIndex >= 0) {
|
|
37
|
+
if (filesIndex !== 0 || remaining.length < 2)
|
|
38
|
+
throw new Error('Usage: specdest check [--refresh] [--staged | --files <path...>]');
|
|
39
|
+
result.mode = 'files';
|
|
40
|
+
result.files = remaining.slice(1);
|
|
41
|
+
return result;
|
|
42
|
+
}
|
|
43
|
+
if (remaining.length)
|
|
44
|
+
throw new Error(`Unknown option: ${remaining[0]}`);
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
function rulesFlags(args) {
|
|
48
|
+
const result = { json: false, ids: [], categories: [], failed: false };
|
|
49
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
50
|
+
const arg = args[index];
|
|
51
|
+
if (arg === '--json')
|
|
52
|
+
result.json = true;
|
|
53
|
+
else if (arg === '--failed')
|
|
54
|
+
result.failed = true;
|
|
55
|
+
else if (arg === '--id' && args[index + 1])
|
|
56
|
+
result.ids.push(args[++index]);
|
|
57
|
+
else if (arg === '--category' && args[index + 1])
|
|
58
|
+
result.categories.push(args[++index]);
|
|
59
|
+
else
|
|
60
|
+
throw new Error(`Unknown option: ${arg}`);
|
|
61
|
+
}
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
export function createCanonicalCommandHandlers(projectRoot = process.cwd(), options = {}) {
|
|
65
|
+
const source = options.source ?? createCanonicalSource(options);
|
|
66
|
+
return {
|
|
67
|
+
add: async (args, io) => {
|
|
68
|
+
if (args.length !== 1) {
|
|
69
|
+
io.stderr.write('Usage: specdest add <package>\n');
|
|
70
|
+
return 2;
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
const result = await addPredefinedPackage(projectRoot, args[0]);
|
|
74
|
+
io.stdout.write(result.changed
|
|
75
|
+
? `Registered ${result.id} (recipe ${result.recipeVersion}, detected ${result.detectedVersion ?? 'unknown'}, ${result.source})\n`
|
|
76
|
+
: `${result.id} already registered (recipe ${result.recipeVersion}, detected ${result.detectedVersion ?? 'unknown'}); no changes.\n`);
|
|
77
|
+
return 0;
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
io.stderr.write(`${error.message}\n`);
|
|
81
|
+
return 1;
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
status: async (args, io) => {
|
|
85
|
+
const parsed = flags(args);
|
|
86
|
+
const result = await canonicalStatus(projectRoot, source, { refresh: parsed.refresh });
|
|
87
|
+
if (parsed.json)
|
|
88
|
+
io.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
89
|
+
else {
|
|
90
|
+
io.stdout.write(`Stack: ${result.stack ?? 'unknown'}\nApplicable: ${result.totals.applicable} Current: ${result.totals.current} Missing: ${result.totals.missing} Outdated: ${result.totals.outdated}\n`);
|
|
91
|
+
if (result.packages.length)
|
|
92
|
+
io.stdout.write(`Packages: ${result.packages.map((item) => `${item.id}@${item.detectedVersion ?? 'unknown'} (recipe ${item.recipeVersion ?? 'unknown'})`).join(', ')}\n`);
|
|
93
|
+
for (const issue of result.packageIssues)
|
|
94
|
+
io.stderr.write(`FAIL ${issue}\n`);
|
|
95
|
+
}
|
|
96
|
+
return result.totals.missing || result.totals.outdated || result.packageIssues.length ? 1 : 0;
|
|
97
|
+
},
|
|
98
|
+
sync: async (args, io) => {
|
|
99
|
+
if (args.length) {
|
|
100
|
+
io.stderr.write('Usage: specdest sync\n');
|
|
101
|
+
return 2;
|
|
102
|
+
}
|
|
103
|
+
const result = await canonicalSync(projectRoot, source);
|
|
104
|
+
io.stdout.write(`Synced ${result.applicable} applicable rules; ${result.changed.length} changed.\n`);
|
|
105
|
+
for (const item of result.changed)
|
|
106
|
+
io.stdout.write(`${item.action.toUpperCase()} ${item.id}@${item.version}\n`);
|
|
107
|
+
return 0;
|
|
108
|
+
},
|
|
109
|
+
check: async (args, io) => {
|
|
110
|
+
let parsed;
|
|
111
|
+
try {
|
|
112
|
+
parsed = checkFlags(args);
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
io.stderr.write(`${error.message}\n`);
|
|
116
|
+
return 2;
|
|
117
|
+
}
|
|
118
|
+
const result = await canonicalCheck(projectRoot, source, parsed);
|
|
119
|
+
for (const [id, check] of Object.entries(result.results))
|
|
120
|
+
io.stdout.write(`${check.status.toUpperCase()} ${id}\n`);
|
|
121
|
+
return result.exitCode;
|
|
122
|
+
},
|
|
123
|
+
rules: async (args, io) => {
|
|
124
|
+
const parsed = rulesFlags(args);
|
|
125
|
+
const result = await canonicalRules(projectRoot, source, parsed);
|
|
126
|
+
if (parsed.json)
|
|
127
|
+
io.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
128
|
+
else {
|
|
129
|
+
for (const rule of result.rules) {
|
|
130
|
+
const body = result.detail ? rule.content.trim() : rule.summary;
|
|
131
|
+
const composition = rule.composedOf.length ? `\nComposed of: ${rule.composedOf.join(', ')}` : '';
|
|
132
|
+
io.stdout.write(`## ${rule.id} — ${rule.name}\n${body}${composition}\n\n`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return 0;
|
|
136
|
+
},
|
|
137
|
+
'ai-instruction': async (args, io) => {
|
|
138
|
+
if (args.length) {
|
|
139
|
+
io.stderr.write('Usage: specdest ai-instruction\n');
|
|
140
|
+
return 2;
|
|
141
|
+
}
|
|
142
|
+
io.stdout.write(`${aiInstructionText()}\n`);
|
|
143
|
+
return 0;
|
|
144
|
+
},
|
|
145
|
+
doctor: async (args, io) => {
|
|
146
|
+
if (args.length) {
|
|
147
|
+
io.stderr.write('Usage: specdest doctor\n');
|
|
148
|
+
return 2;
|
|
149
|
+
}
|
|
150
|
+
const result = await canonicalDoctor(projectRoot, source);
|
|
151
|
+
io.stdout.write(`Cache: ${result.cacheRoot}\nStack: ${result.stack ?? 'unknown'}\n`);
|
|
152
|
+
for (const issue of result.issues)
|
|
153
|
+
io.stderr.write(`FAIL ${issue}\n`);
|
|
154
|
+
return result.ok ? 0 : 1;
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export declare const FLOW_WORKFLOWS: Readonly<{
|
|
2
|
+
feature: readonly string[];
|
|
3
|
+
fix: readonly string[];
|
|
4
|
+
inspect: readonly string[];
|
|
5
|
+
}>;
|
|
6
|
+
type FlowMode = keyof typeof FLOW_WORKFLOWS;
|
|
7
|
+
type FlowPhase = 'plan' | 'implement' | 'verify';
|
|
8
|
+
type VerificationStatus = 'pending' | 'running' | 'failed' | 'passed';
|
|
9
|
+
type FlowTask = {
|
|
10
|
+
id: string;
|
|
11
|
+
mode: FlowMode;
|
|
12
|
+
phase: FlowPhase;
|
|
13
|
+
goal: string;
|
|
14
|
+
contextFile: string | null;
|
|
15
|
+
verification: {
|
|
16
|
+
status: VerificationStatus;
|
|
17
|
+
fingerprint: string | null;
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
type FlowState = {
|
|
21
|
+
schemaVersion: 1;
|
|
22
|
+
selectedTaskId: string | null;
|
|
23
|
+
tasks: FlowTask[];
|
|
24
|
+
};
|
|
25
|
+
type FlowIo = {
|
|
26
|
+
stdout: {
|
|
27
|
+
write(value: string): unknown;
|
|
28
|
+
};
|
|
29
|
+
stderr: {
|
|
30
|
+
write(value: string): unknown;
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
type VerificationResult = {
|
|
34
|
+
exitCode: number;
|
|
35
|
+
stdout: string;
|
|
36
|
+
stderr: string;
|
|
37
|
+
summary: string;
|
|
38
|
+
};
|
|
39
|
+
type FlowDependencies = {
|
|
40
|
+
verify: (projectRoot: string) => Promise<VerificationResult>;
|
|
41
|
+
fingerprint: (projectRoot: string) => Promise<string>;
|
|
42
|
+
};
|
|
43
|
+
export declare function transitionPhase(mode: FlowMode, currentPhase: string, nextPhase: string): string;
|
|
44
|
+
export declare function readFlowState(projectRoot: string): Promise<FlowState>;
|
|
45
|
+
export declare function runConfiguredVerification(projectRoot: string): Promise<VerificationResult>;
|
|
46
|
+
export declare function repositoryFingerprint(projectRoot: string): Promise<string>;
|
|
47
|
+
export declare function createFlowCommandHandler(projectRoot?: string, options?: Partial<FlowDependencies>): (args: string[], io: FlowIo) => Promise<number>;
|
|
48
|
+
export {};
|
package/dist/npm/flow.js
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { access, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { dirname, join, normalize } from 'node:path';
|
|
5
|
+
export const FLOW_WORKFLOWS = Object.freeze({
|
|
6
|
+
feature: Object.freeze(['plan', 'implement', 'verify', 'complete']),
|
|
7
|
+
fix: Object.freeze(['plan', 'implement', 'verify', 'complete']),
|
|
8
|
+
inspect: Object.freeze(['plan', 'complete']),
|
|
9
|
+
});
|
|
10
|
+
const FLOW_STATE_PATH = '.spd/flow.json';
|
|
11
|
+
const EMPTY_STATE = Object.freeze({
|
|
12
|
+
schemaVersion: 1,
|
|
13
|
+
selectedTaskId: null,
|
|
14
|
+
tasks: [],
|
|
15
|
+
});
|
|
16
|
+
function cloneState(state) {
|
|
17
|
+
return JSON.parse(JSON.stringify(state));
|
|
18
|
+
}
|
|
19
|
+
function execute(command, args, cwd) {
|
|
20
|
+
return new Promise((resolve, reject) => {
|
|
21
|
+
const child = spawn(command, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
22
|
+
let stdout = '';
|
|
23
|
+
let stderr = '';
|
|
24
|
+
child.stdout.setEncoding('utf8');
|
|
25
|
+
child.stderr.setEncoding('utf8');
|
|
26
|
+
child.stdout.on('data', (chunk) => { stdout += chunk; });
|
|
27
|
+
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
28
|
+
child.on('error', reject);
|
|
29
|
+
child.on('close', (code) => resolve({
|
|
30
|
+
exitCode: code ?? 1,
|
|
31
|
+
stdout,
|
|
32
|
+
stderr,
|
|
33
|
+
summary: [command, ...args].join(' '),
|
|
34
|
+
}));
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
async function exists(path) {
|
|
38
|
+
try {
|
|
39
|
+
await access(path);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error.code === 'ENOENT')
|
|
44
|
+
return false;
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function validateMode(value) {
|
|
49
|
+
if (!(value in FLOW_WORKFLOWS))
|
|
50
|
+
throw new Error(`Unsupported flow mode: ${value}`);
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
function validateTaskId(value) {
|
|
54
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(value)) {
|
|
55
|
+
throw new Error('Task id must be a readable lowercase slug (letters, numbers, hyphens).');
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
function slugify(value) {
|
|
60
|
+
return value.toLowerCase()
|
|
61
|
+
.replace(/[^a-z0-9]+/gu, '-')
|
|
62
|
+
.replace(/^-|-$/gu, '')
|
|
63
|
+
.slice(0, 64)
|
|
64
|
+
.replace(/-$/u, '') || 'task';
|
|
65
|
+
}
|
|
66
|
+
function validateContextFile(value) {
|
|
67
|
+
if (!value)
|
|
68
|
+
return null;
|
|
69
|
+
const path = normalize(value).replaceAll('\\', '/');
|
|
70
|
+
if (path === '..' || path.startsWith('../') || path.startsWith('/') || !path.startsWith('flow-notes/')) {
|
|
71
|
+
throw new Error('Context file must be relative to .spd/flow-notes/.');
|
|
72
|
+
}
|
|
73
|
+
return path;
|
|
74
|
+
}
|
|
75
|
+
function validateState(value) {
|
|
76
|
+
const state = value;
|
|
77
|
+
if (state?.schemaVersion !== 1 || !Array.isArray(state.tasks)) {
|
|
78
|
+
throw new Error('Invalid .spd/flow.json state');
|
|
79
|
+
}
|
|
80
|
+
const ids = new Set();
|
|
81
|
+
for (const task of state.tasks) {
|
|
82
|
+
validateTaskId(task.id);
|
|
83
|
+
const workflow = FLOW_WORKFLOWS[validateMode(task.mode)];
|
|
84
|
+
const phase = String(task.phase);
|
|
85
|
+
if (!workflow.includes(phase) || phase === 'complete') {
|
|
86
|
+
throw new Error(`Invalid flow phase for task ${task.id}: ${phase}`);
|
|
87
|
+
}
|
|
88
|
+
if (ids.has(task.id))
|
|
89
|
+
throw new Error(`Duplicate flow task id: ${task.id}`);
|
|
90
|
+
ids.add(task.id);
|
|
91
|
+
}
|
|
92
|
+
if (state.selectedTaskId !== null && !ids.has(state.selectedTaskId)) {
|
|
93
|
+
throw new Error('Selected flow task does not exist.');
|
|
94
|
+
}
|
|
95
|
+
return state;
|
|
96
|
+
}
|
|
97
|
+
export function transitionPhase(mode, currentPhase, nextPhase) {
|
|
98
|
+
const workflow = FLOW_WORKFLOWS[mode];
|
|
99
|
+
const currentIndex = workflow.indexOf(currentPhase);
|
|
100
|
+
if (currentIndex < 0 || workflow[currentIndex + 1] !== nextPhase) {
|
|
101
|
+
throw new Error(`Invalid flow transition for ${mode}: ${currentPhase} -> ${nextPhase}`);
|
|
102
|
+
}
|
|
103
|
+
return nextPhase;
|
|
104
|
+
}
|
|
105
|
+
export async function readFlowState(projectRoot) {
|
|
106
|
+
try {
|
|
107
|
+
return validateState(JSON.parse(await readFile(join(projectRoot, FLOW_STATE_PATH), 'utf8')));
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (error.code === 'ENOENT')
|
|
111
|
+
return cloneState(EMPTY_STATE);
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async function writeFlowState(projectRoot, state) {
|
|
116
|
+
validateState(state);
|
|
117
|
+
const path = join(projectRoot, FLOW_STATE_PATH);
|
|
118
|
+
await mkdir(dirname(path), { recursive: true });
|
|
119
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
120
|
+
await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
|
|
121
|
+
await rename(temporary, path);
|
|
122
|
+
}
|
|
123
|
+
async function ensureFlowIgnored(projectRoot) {
|
|
124
|
+
const gitPath = await execute('git', ['rev-parse', '--git-path', 'info/exclude'], projectRoot);
|
|
125
|
+
const excludePath = gitPath.exitCode === 0
|
|
126
|
+
? (gitPath.stdout.trim().startsWith('/') ? gitPath.stdout.trim() : join(projectRoot, gitPath.stdout.trim()))
|
|
127
|
+
: join(projectRoot, '.git', 'info', 'exclude');
|
|
128
|
+
await mkdir(dirname(excludePath), { recursive: true });
|
|
129
|
+
let content = '';
|
|
130
|
+
try {
|
|
131
|
+
content = await readFile(excludePath, 'utf8');
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
if (error.code !== 'ENOENT')
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
if (content.split(/\r?\n/u).includes('/.spd/'))
|
|
138
|
+
return;
|
|
139
|
+
const separator = content && !content.endsWith('\n') ? '\n' : '';
|
|
140
|
+
await writeFile(excludePath, `${content}${separator}/.spd/\n`, 'utf8');
|
|
141
|
+
}
|
|
142
|
+
function parseOptions(args, allowed) {
|
|
143
|
+
const result = {};
|
|
144
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
145
|
+
const argument = args[index];
|
|
146
|
+
if (!allowed.has(argument))
|
|
147
|
+
throw new Error(`Unknown option: ${argument}`);
|
|
148
|
+
if (argument === '--json') {
|
|
149
|
+
result.json = true;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const value = args[++index];
|
|
153
|
+
if (!value || value.startsWith('--'))
|
|
154
|
+
throw new Error(`Missing value for ${argument}`);
|
|
155
|
+
const key = argument.slice(2).replace(/-([a-z])/gu, (_, letter) => letter.toUpperCase());
|
|
156
|
+
result[key] = value;
|
|
157
|
+
}
|
|
158
|
+
return result;
|
|
159
|
+
}
|
|
160
|
+
function selectTask(state, requestedTaskId) {
|
|
161
|
+
const taskId = requestedTaskId || state.selectedTaskId || (state.tasks.length === 1 ? state.tasks[0]?.id : null);
|
|
162
|
+
if (!taskId)
|
|
163
|
+
throw new Error('Multiple tasks exist; select one with --task <id>.');
|
|
164
|
+
const task = state.tasks.find((candidate) => candidate.id === taskId);
|
|
165
|
+
if (!task)
|
|
166
|
+
throw new Error(`Unknown flow task: ${taskId}`);
|
|
167
|
+
return task;
|
|
168
|
+
}
|
|
169
|
+
function resetVerification(task) {
|
|
170
|
+
task.verification = { status: 'pending', fingerprint: null };
|
|
171
|
+
}
|
|
172
|
+
async function startFlow(projectRoot, args, io) {
|
|
173
|
+
const options = parseOptions(args, new Set(['--mode', '--task', '--goal', '--context-file']));
|
|
174
|
+
const mode = validateMode(String(options.mode || ''));
|
|
175
|
+
const goal = String(options.goal || '').trim();
|
|
176
|
+
if (!goal) {
|
|
177
|
+
throw new Error('Usage: specdest flow start --mode <feature|fix|inspect> --goal <text> [--task <id>] [--context-file <path>]');
|
|
178
|
+
}
|
|
179
|
+
const taskId = validateTaskId(options.task ? String(options.task) : slugify(goal));
|
|
180
|
+
const state = await readFlowState(projectRoot);
|
|
181
|
+
if (state.tasks.some((task) => task.id === taskId))
|
|
182
|
+
throw new Error(`Flow task already exists: ${taskId}`);
|
|
183
|
+
state.tasks.push({
|
|
184
|
+
id: taskId,
|
|
185
|
+
mode,
|
|
186
|
+
phase: 'plan',
|
|
187
|
+
goal,
|
|
188
|
+
contextFile: validateContextFile(options.contextFile ? String(options.contextFile) : undefined),
|
|
189
|
+
verification: { status: 'pending', fingerprint: null },
|
|
190
|
+
});
|
|
191
|
+
state.selectedTaskId = taskId;
|
|
192
|
+
await ensureFlowIgnored(projectRoot);
|
|
193
|
+
await writeFlowState(projectRoot, state);
|
|
194
|
+
io.stdout.write(`Started ${taskId} (${mode}) at plan.\n`);
|
|
195
|
+
return 0;
|
|
196
|
+
}
|
|
197
|
+
async function flowStatus(projectRoot, args, io) {
|
|
198
|
+
const options = parseOptions(args, new Set(['--json']));
|
|
199
|
+
const state = await readFlowState(projectRoot);
|
|
200
|
+
if (options.json) {
|
|
201
|
+
io.stdout.write(`${JSON.stringify(state, null, 2)}\n`);
|
|
202
|
+
return 0;
|
|
203
|
+
}
|
|
204
|
+
if (!state.tasks.length) {
|
|
205
|
+
io.stdout.write('No active flow tasks.\n');
|
|
206
|
+
return 0;
|
|
207
|
+
}
|
|
208
|
+
io.stdout.write(`Selected: ${state.selectedTaskId ?? 'none'}\n`);
|
|
209
|
+
for (const task of state.tasks) {
|
|
210
|
+
const context = task.contextFile ? ` context=.spd/${task.contextFile}` : '';
|
|
211
|
+
io.stdout.write(`${task.id}: ${task.mode} phase=${task.phase} verification=${task.verification.status} goal=${task.goal}${context}\n`);
|
|
212
|
+
}
|
|
213
|
+
return 0;
|
|
214
|
+
}
|
|
215
|
+
async function checkpointFlow(projectRoot, args, io) {
|
|
216
|
+
const options = parseOptions(args, new Set(['--task', '--phase', '--context-file']));
|
|
217
|
+
const targetPhase = String(options.phase || '');
|
|
218
|
+
if (!targetPhase)
|
|
219
|
+
throw new Error('Usage: specdest flow checkpoint --phase <phase> [--task <id>] [--context-file <path>]');
|
|
220
|
+
const state = await readFlowState(projectRoot);
|
|
221
|
+
const task = selectTask(state, options.task ? String(options.task) : undefined);
|
|
222
|
+
if (targetPhase !== task.phase) {
|
|
223
|
+
transitionPhase(task.mode, task.phase, targetPhase);
|
|
224
|
+
if (targetPhase === 'verify' || targetPhase === 'complete') {
|
|
225
|
+
throw new Error(`Use flow ${targetPhase === 'verify' ? 'verify' : 'complete'} for the ${targetPhase} phase.`);
|
|
226
|
+
}
|
|
227
|
+
task.phase = targetPhase;
|
|
228
|
+
resetVerification(task);
|
|
229
|
+
}
|
|
230
|
+
if (options.contextFile !== undefined)
|
|
231
|
+
task.contextFile = validateContextFile(String(options.contextFile));
|
|
232
|
+
state.selectedTaskId = task.id;
|
|
233
|
+
await ensureFlowIgnored(projectRoot);
|
|
234
|
+
await writeFlowState(projectRoot, state);
|
|
235
|
+
io.stdout.write(`Checkpointed ${task.id} at ${task.phase}.\n`);
|
|
236
|
+
return 0;
|
|
237
|
+
}
|
|
238
|
+
async function projectPackageManager(projectRoot, packageJson) {
|
|
239
|
+
const declared = String(packageJson.packageManager || '').split('@')[0];
|
|
240
|
+
if (declared)
|
|
241
|
+
return declared;
|
|
242
|
+
if (await exists(join(projectRoot, 'pnpm-lock.yaml')))
|
|
243
|
+
return 'pnpm';
|
|
244
|
+
if (await exists(join(projectRoot, 'yarn.lock')))
|
|
245
|
+
return 'yarn';
|
|
246
|
+
if (await exists(join(projectRoot, 'bun.lockb')) || await exists(join(projectRoot, 'bun.lock')))
|
|
247
|
+
return 'bun';
|
|
248
|
+
return 'npm';
|
|
249
|
+
}
|
|
250
|
+
export async function runConfiguredVerification(projectRoot) {
|
|
251
|
+
const prePush = join(projectRoot, '.husky', 'pre-push');
|
|
252
|
+
if (await exists(prePush))
|
|
253
|
+
return await execute('sh', [prePush], projectRoot);
|
|
254
|
+
let packageJson;
|
|
255
|
+
try {
|
|
256
|
+
packageJson = JSON.parse(await readFile(join(projectRoot, 'package.json'), 'utf8'));
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
if (error.code === 'ENOENT') {
|
|
260
|
+
return { exitCode: 1, stdout: '', stderr: 'No .husky/pre-push or package.json verification gate found.\n', summary: 'missing verification gate' };
|
|
261
|
+
}
|
|
262
|
+
throw error;
|
|
263
|
+
}
|
|
264
|
+
if (!packageJson.scripts?.check) {
|
|
265
|
+
return { exitCode: 1, stdout: '', stderr: 'No .husky/pre-push or package.json check script found.\n', summary: 'missing verification gate' };
|
|
266
|
+
}
|
|
267
|
+
const manager = await projectPackageManager(projectRoot, packageJson);
|
|
268
|
+
const commandArgs = manager === 'yarn' ? ['check'] : ['run', 'check'];
|
|
269
|
+
return await execute(manager, commandArgs, projectRoot);
|
|
270
|
+
}
|
|
271
|
+
export async function repositoryFingerprint(projectRoot) {
|
|
272
|
+
const [head, diff, status] = await Promise.all([
|
|
273
|
+
execute('git', ['rev-parse', 'HEAD'], projectRoot),
|
|
274
|
+
execute('git', ['diff', '--binary', 'HEAD', '--', '.'], projectRoot),
|
|
275
|
+
execute('git', ['status', '--porcelain=v1', '-z', '--untracked-files=all'], projectRoot),
|
|
276
|
+
]);
|
|
277
|
+
if ([head, diff, status].some((result) => result.exitCode !== 0)) {
|
|
278
|
+
throw new Error('Unable to fingerprint repository Git/worktree state.');
|
|
279
|
+
}
|
|
280
|
+
const hash = createHash('sha256');
|
|
281
|
+
hash.update(head.stdout);
|
|
282
|
+
hash.update(diff.stdout);
|
|
283
|
+
const entries = status.stdout.split('\0')
|
|
284
|
+
.filter(Boolean)
|
|
285
|
+
.filter((entry) => !entry.slice(3).startsWith('.spd/'));
|
|
286
|
+
hash.update(entries.join('\0'));
|
|
287
|
+
for (const entry of entries) {
|
|
288
|
+
if (!entry.startsWith('?? '))
|
|
289
|
+
continue;
|
|
290
|
+
try {
|
|
291
|
+
hash.update(entry.slice(3));
|
|
292
|
+
hash.update(await readFile(join(projectRoot, entry.slice(3))));
|
|
293
|
+
}
|
|
294
|
+
catch (error) {
|
|
295
|
+
const code = error.code;
|
|
296
|
+
if (code !== 'EISDIR' && code !== 'ENOENT')
|
|
297
|
+
throw error;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return hash.digest('hex');
|
|
301
|
+
}
|
|
302
|
+
async function verifyFlow(projectRoot, args, io, dependencies) {
|
|
303
|
+
const options = parseOptions(args, new Set(['--task']));
|
|
304
|
+
const state = await readFlowState(projectRoot);
|
|
305
|
+
const task = selectTask(state, options.task ? String(options.task) : undefined);
|
|
306
|
+
if (task.mode === 'inspect')
|
|
307
|
+
throw new Error('Inspect flows do not have a verify phase.');
|
|
308
|
+
if (task.phase === 'plan')
|
|
309
|
+
throw new Error('Checkpoint implement before verification.');
|
|
310
|
+
if (task.phase !== 'implement' && task.phase !== 'verify')
|
|
311
|
+
throw new Error(`Cannot verify task from phase: ${task.phase}`);
|
|
312
|
+
task.phase = 'verify';
|
|
313
|
+
task.verification = { status: 'running', fingerprint: null };
|
|
314
|
+
state.selectedTaskId = task.id;
|
|
315
|
+
await writeFlowState(projectRoot, state);
|
|
316
|
+
const result = await dependencies.verify(projectRoot);
|
|
317
|
+
if (result.stdout)
|
|
318
|
+
io.stdout.write(result.stdout);
|
|
319
|
+
if (result.stderr)
|
|
320
|
+
io.stderr.write(result.stderr);
|
|
321
|
+
if (result.exitCode !== 0) {
|
|
322
|
+
task.verification = { status: 'failed', fingerprint: null };
|
|
323
|
+
await writeFlowState(projectRoot, state);
|
|
324
|
+
io.stderr.write(`Verification failed for ${task.id} via ${result.summary}.\n`);
|
|
325
|
+
return 1;
|
|
326
|
+
}
|
|
327
|
+
task.verification = { status: 'passed', fingerprint: await dependencies.fingerprint(projectRoot) };
|
|
328
|
+
await writeFlowState(projectRoot, state);
|
|
329
|
+
io.stdout.write(`Verification passed for ${task.id} via ${result.summary}.\n`);
|
|
330
|
+
return 0;
|
|
331
|
+
}
|
|
332
|
+
async function cleanupTask(projectRoot, state, task) {
|
|
333
|
+
if (task.contextFile)
|
|
334
|
+
await rm(join(projectRoot, '.spd', task.contextFile), { force: true });
|
|
335
|
+
state.tasks = state.tasks.filter((candidate) => candidate.id !== task.id);
|
|
336
|
+
state.selectedTaskId = state.tasks[0]?.id ?? null;
|
|
337
|
+
if (!state.tasks.length) {
|
|
338
|
+
await rm(join(projectRoot, '.spd'), { recursive: true, force: true });
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
await writeFlowState(projectRoot, state);
|
|
342
|
+
}
|
|
343
|
+
async function completeFlow(projectRoot, args, io, dependencies) {
|
|
344
|
+
const options = parseOptions(args, new Set(['--task']));
|
|
345
|
+
const state = await readFlowState(projectRoot);
|
|
346
|
+
const task = selectTask(state, options.task ? String(options.task) : undefined);
|
|
347
|
+
if (task.mode === 'inspect') {
|
|
348
|
+
transitionPhase(task.mode, task.phase, 'complete');
|
|
349
|
+
await cleanupTask(projectRoot, state, task);
|
|
350
|
+
io.stdout.write(`Completed ${task.id}.\n`);
|
|
351
|
+
return 0;
|
|
352
|
+
}
|
|
353
|
+
if (task.phase !== 'verify' || task.verification.status !== 'passed') {
|
|
354
|
+
io.stderr.write(`Cannot complete ${task.id}: verification has not passed.\n`);
|
|
355
|
+
return 1;
|
|
356
|
+
}
|
|
357
|
+
if (await dependencies.fingerprint(projectRoot) !== task.verification.fingerprint) {
|
|
358
|
+
io.stderr.write(`Cannot complete ${task.id}: verification is stale; rerun flow verify.\n`);
|
|
359
|
+
return 1;
|
|
360
|
+
}
|
|
361
|
+
transitionPhase(task.mode, task.phase, 'complete');
|
|
362
|
+
await cleanupTask(projectRoot, state, task);
|
|
363
|
+
io.stdout.write(`Completed ${task.id}.\n`);
|
|
364
|
+
return 0;
|
|
365
|
+
}
|
|
366
|
+
export function createFlowCommandHandler(projectRoot = process.cwd(), options = {}) {
|
|
367
|
+
const dependencies = {
|
|
368
|
+
verify: options.verify ?? runConfiguredVerification,
|
|
369
|
+
fingerprint: options.fingerprint ?? repositoryFingerprint,
|
|
370
|
+
};
|
|
371
|
+
return async (args, io) => {
|
|
372
|
+
const [subcommand, ...rest] = args;
|
|
373
|
+
try {
|
|
374
|
+
if (!subcommand || ['help', '--help', '-h'].includes(subcommand)) {
|
|
375
|
+
io.stdout.write('Usage: specdest flow <status|start|checkpoint|verify|complete> [options]\n');
|
|
376
|
+
return 0;
|
|
377
|
+
}
|
|
378
|
+
if (subcommand === 'status')
|
|
379
|
+
return await flowStatus(projectRoot, rest, io);
|
|
380
|
+
if (subcommand === 'start')
|
|
381
|
+
return await startFlow(projectRoot, rest, io);
|
|
382
|
+
if (subcommand === 'checkpoint')
|
|
383
|
+
return await checkpointFlow(projectRoot, rest, io);
|
|
384
|
+
if (subcommand === 'verify')
|
|
385
|
+
return await verifyFlow(projectRoot, rest, io, dependencies);
|
|
386
|
+
if (subcommand === 'complete')
|
|
387
|
+
return await completeFlow(projectRoot, rest, io, dependencies);
|
|
388
|
+
io.stderr.write(`Unknown flow command: ${subcommand}\n`);
|
|
389
|
+
return 2;
|
|
390
|
+
}
|
|
391
|
+
catch (error) {
|
|
392
|
+
io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
393
|
+
return 2;
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
}
|