-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathshared.ts
More file actions
215 lines (193 loc) · 6.4 KB
/
shared.ts
File metadata and controls
215 lines (193 loc) · 6.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/**
* Shared Types and Utilities for Artifact Workflow Commands
*
* This module contains types, constants, and validation helpers used across
* multiple artifact workflow commands.
*/
import chalk from 'chalk';
import path from 'path';
import * as fs from 'fs';
import { getSchemaDir, listSchemas } from '../../core/artifact-graph/index.js';
import { validateChangeName } from '../../utils/change-utils.js';
import { readProjectConfig, RESERVED_PHASE_IDS } from '../../core/project-config.js';
// -----------------------------------------------------------------------------
// Types
// -----------------------------------------------------------------------------
export interface TaskItem {
id: string;
description: string;
done: boolean;
}
export interface ApplyInstructions {
changeName: string;
changeDir: string;
schemaName: string;
contextFiles: Record<string, string>;
progress: {
total: number;
complete: number;
remaining: number;
};
tasks: TaskItem[];
state: 'blocked' | 'all_done' | 'ready';
missingArtifacts?: string[];
instruction: string;
context?: string;
rules?: string[];
}
export interface VerifyInstructions {
changeName: string;
changeDir: string;
schemaName: string;
contextFiles: Record<string, string>;
progress: {
total: number;
complete: number;
remaining: number;
};
tasks: TaskItem[];
context?: string;
rules?: string[];
}
// Re-export RESERVED_PHASE_IDS for convenience
export { RESERVED_PHASE_IDS } from '../../core/project-config.js';
/**
* Reads project config and extracts context + phase-specific rules.
* Centralizes the config-reading logic used by both apply and verify phases.
*
* @param projectRoot - The root directory of the project
* @param phase - The phase to read rules for ('apply' | 'verify')
* @returns Object with optional context and rules, or empty object on failure
*/
export function readPhaseConfig(
projectRoot: string,
phase: 'apply' | 'verify'
): { context?: string; rules?: string[] } {
try {
const projectConfig = readProjectConfig(projectRoot);
const result: { context?: string; rules?: string[] } = {};
if (projectConfig?.context?.trim()) {
result.context = projectConfig.context.trim();
}
if (projectConfig?.rules?.[phase] && projectConfig.rules[phase].length > 0) {
result.rules = projectConfig.rules[phase];
}
return result;
} catch {
// If config read fails, continue without config
return {};
}
}
// -----------------------------------------------------------------------------
// Constants
// -----------------------------------------------------------------------------
export const DEFAULT_SCHEMA = 'spec-driven';
// -----------------------------------------------------------------------------
// Utility Functions
// -----------------------------------------------------------------------------
/**
* Checks if color output is disabled via NO_COLOR env or --no-color flag.
*/
export function isColorDisabled(): boolean {
return process.env.NO_COLOR === '1' || process.env.NO_COLOR === 'true';
}
/**
* Gets the color function based on status.
*/
export function getStatusColor(status: 'done' | 'ready' | 'blocked'): (text: string) => string {
if (isColorDisabled()) {
return (text: string) => text;
}
switch (status) {
case 'done':
return chalk.green;
case 'ready':
return chalk.yellow;
case 'blocked':
return chalk.red;
}
}
/**
* Gets the status indicator for an artifact.
*/
export function getStatusIndicator(status: 'done' | 'ready' | 'blocked'): string {
const color = getStatusColor(status);
switch (status) {
case 'done':
return color('[x]');
case 'ready':
return color('[ ]');
case 'blocked':
return color('[-]');
}
}
/**
* Returns the list of available change directory names under openspec/changes/.
* Excludes the archive directory and hidden directories.
*/
export async function getAvailableChanges(projectRoot: string): Promise<string[]> {
const changesPath = path.join(projectRoot, 'openspec', 'changes');
try {
const entries = await fs.promises.readdir(changesPath, { withFileTypes: true });
return entries
.filter((e) => e.isDirectory() && e.name !== 'archive' && !e.name.startsWith('.'))
.map((e) => e.name);
} catch (error: unknown) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
throw error;
}
}
/**
* Validates that a change exists and returns available changes if not.
* Checks directory existence directly to support scaffolded changes (without proposal.md).
*/
export async function validateChangeExists(
changeName: string | undefined,
projectRoot: string
): Promise<string> {
if (!changeName) {
const available = await getAvailableChanges(projectRoot);
if (available.length === 0) {
throw new Error('No changes found. Create one with: openspec new change <name>');
}
throw new Error(
`Missing required option --change. Available changes:\n ${available.join('\n ')}`
);
}
// Validate change name format to prevent path traversal
const nameValidation = validateChangeName(changeName);
if (!nameValidation.valid) {
throw new Error(`Invalid change name '${changeName}': ${nameValidation.error}`);
}
// Check directory existence directly
const changePath = path.join(projectRoot, 'openspec', 'changes', changeName);
const exists = fs.existsSync(changePath) && fs.statSync(changePath).isDirectory();
if (!exists) {
const available = await getAvailableChanges(projectRoot);
if (available.length === 0) {
throw new Error(
`Change '${changeName}' not found. No changes exist. Create one with: openspec new change <name>`
);
}
throw new Error(
`Change '${changeName}' not found. Available changes:\n ${available.join('\n ')}`
);
}
return changeName;
}
/**
* Validates that a schema exists and returns available schemas if not.
*
* @param schemaName - The schema name to validate
* @param projectRoot - Optional project root for project-local schema resolution
*/
export function validateSchemaExists(schemaName: string, projectRoot?: string): string {
const schemaDir = getSchemaDir(schemaName, projectRoot);
if (!schemaDir) {
const availableSchemas = listSchemas(projectRoot);
throw new Error(
`Schema '${schemaName}' not found. Available schemas:\n ${availableSchemas.join('\n ')}`
);
}
return schemaName;
}