@zhuan-ai/zhuanspec 1.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 (210) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +461 -0
  3. package/README.zh.md +434 -0
  4. package/bin/zhuanspec.js +3 -0
  5. package/dist/cli/index.d.ts +2 -0
  6. package/dist/cli/index.js +356 -0
  7. package/dist/commands/artifact-workflow.d.ts +13 -0
  8. package/dist/commands/artifact-workflow.js +916 -0
  9. package/dist/commands/change.d.ts +35 -0
  10. package/dist/commands/change.js +277 -0
  11. package/dist/commands/completion.d.ts +72 -0
  12. package/dist/commands/completion.js +221 -0
  13. package/dist/commands/config.d.ts +8 -0
  14. package/dist/commands/config.js +198 -0
  15. package/dist/commands/show.d.ts +14 -0
  16. package/dist/commands/show.js +132 -0
  17. package/dist/commands/spec.d.ts +15 -0
  18. package/dist/commands/spec.js +225 -0
  19. package/dist/commands/validate.d.ts +24 -0
  20. package/dist/commands/validate.js +294 -0
  21. package/dist/core/archive.d.ts +30 -0
  22. package/dist/core/archive.js +438 -0
  23. package/dist/core/artifact-graph/graph.d.ts +56 -0
  24. package/dist/core/artifact-graph/graph.js +141 -0
  25. package/dist/core/artifact-graph/index.d.ts +7 -0
  26. package/dist/core/artifact-graph/index.js +13 -0
  27. package/dist/core/artifact-graph/instruction-loader.d.ts +134 -0
  28. package/dist/core/artifact-graph/instruction-loader.js +180 -0
  29. package/dist/core/artifact-graph/resolver.d.ts +61 -0
  30. package/dist/core/artifact-graph/resolver.js +187 -0
  31. package/dist/core/artifact-graph/schema.d.ts +13 -0
  32. package/dist/core/artifact-graph/schema.js +108 -0
  33. package/dist/core/artifact-graph/state.d.ts +12 -0
  34. package/dist/core/artifact-graph/state.js +54 -0
  35. package/dist/core/artifact-graph/types.d.ts +45 -0
  36. package/dist/core/artifact-graph/types.js +43 -0
  37. package/dist/core/completions/command-registry.d.ts +7 -0
  38. package/dist/core/completions/command-registry.js +362 -0
  39. package/dist/core/completions/completion-provider.d.ts +60 -0
  40. package/dist/core/completions/completion-provider.js +102 -0
  41. package/dist/core/completions/factory.d.ts +51 -0
  42. package/dist/core/completions/factory.js +57 -0
  43. package/dist/core/completions/generators/zsh-generator.d.ts +58 -0
  44. package/dist/core/completions/generators/zsh-generator.js +319 -0
  45. package/dist/core/completions/installers/zsh-installer.d.ts +136 -0
  46. package/dist/core/completions/installers/zsh-installer.js +449 -0
  47. package/dist/core/completions/types.d.ts +78 -0
  48. package/dist/core/completions/types.js +2 -0
  49. package/dist/core/config-schema.d.ts +76 -0
  50. package/dist/core/config-schema.js +200 -0
  51. package/dist/core/config.d.ts +16 -0
  52. package/dist/core/config.js +29 -0
  53. package/dist/core/configurators/agents.d.ts +8 -0
  54. package/dist/core/configurators/agents.js +15 -0
  55. package/dist/core/configurators/base.d.ts +7 -0
  56. package/dist/core/configurators/base.js +2 -0
  57. package/dist/core/configurators/claude.d.ts +8 -0
  58. package/dist/core/configurators/claude.js +15 -0
  59. package/dist/core/configurators/cline.d.ts +8 -0
  60. package/dist/core/configurators/cline.js +15 -0
  61. package/dist/core/configurators/codebuddy.d.ts +8 -0
  62. package/dist/core/configurators/codebuddy.js +15 -0
  63. package/dist/core/configurators/costrict.d.ts +8 -0
  64. package/dist/core/configurators/costrict.js +15 -0
  65. package/dist/core/configurators/iflow.d.ts +8 -0
  66. package/dist/core/configurators/iflow.js +15 -0
  67. package/dist/core/configurators/qoder.d.ts +30 -0
  68. package/dist/core/configurators/qoder.js +42 -0
  69. package/dist/core/configurators/qwen.d.ts +24 -0
  70. package/dist/core/configurators/qwen.js +37 -0
  71. package/dist/core/configurators/registry.d.ts +9 -0
  72. package/dist/core/configurators/registry.js +43 -0
  73. package/dist/core/configurators/slash/amazon-q.d.ts +9 -0
  74. package/dist/core/configurators/slash/amazon-q.js +46 -0
  75. package/dist/core/configurators/slash/antigravity.d.ts +9 -0
  76. package/dist/core/configurators/slash/antigravity.js +23 -0
  77. package/dist/core/configurators/slash/auggie.d.ts +9 -0
  78. package/dist/core/configurators/slash/auggie.js +31 -0
  79. package/dist/core/configurators/slash/base.d.ts +19 -0
  80. package/dist/core/configurators/slash/base.js +69 -0
  81. package/dist/core/configurators/slash/claude.d.ts +9 -0
  82. package/dist/core/configurators/slash/claude.js +37 -0
  83. package/dist/core/configurators/slash/cline.d.ts +9 -0
  84. package/dist/core/configurators/slash/cline.js +23 -0
  85. package/dist/core/configurators/slash/codebuddy.d.ts +9 -0
  86. package/dist/core/configurators/slash/codebuddy.js +37 -0
  87. package/dist/core/configurators/slash/codex.d.ts +14 -0
  88. package/dist/core/configurators/slash/codex.js +109 -0
  89. package/dist/core/configurators/slash/costrict.d.ts +9 -0
  90. package/dist/core/configurators/slash/costrict.js +31 -0
  91. package/dist/core/configurators/slash/crush.d.ts +9 -0
  92. package/dist/core/configurators/slash/crush.js +37 -0
  93. package/dist/core/configurators/slash/cursor.d.ts +9 -0
  94. package/dist/core/configurators/slash/cursor.js +37 -0
  95. package/dist/core/configurators/slash/factory.d.ts +10 -0
  96. package/dist/core/configurators/slash/factory.js +35 -0
  97. package/dist/core/configurators/slash/gemini.d.ts +9 -0
  98. package/dist/core/configurators/slash/gemini.js +22 -0
  99. package/dist/core/configurators/slash/github-copilot.d.ts +9 -0
  100. package/dist/core/configurators/slash/github-copilot.js +34 -0
  101. package/dist/core/configurators/slash/iflow.d.ts +9 -0
  102. package/dist/core/configurators/slash/iflow.js +37 -0
  103. package/dist/core/configurators/slash/kilocode.d.ts +9 -0
  104. package/dist/core/configurators/slash/kilocode.js +17 -0
  105. package/dist/core/configurators/slash/opencode.d.ts +12 -0
  106. package/dist/core/configurators/slash/opencode.js +72 -0
  107. package/dist/core/configurators/slash/qoder.d.ts +35 -0
  108. package/dist/core/configurators/slash/qoder.js +76 -0
  109. package/dist/core/configurators/slash/qwen.d.ts +32 -0
  110. package/dist/core/configurators/slash/qwen.js +49 -0
  111. package/dist/core/configurators/slash/registry.d.ts +8 -0
  112. package/dist/core/configurators/slash/registry.js +75 -0
  113. package/dist/core/configurators/slash/roocode.d.ts +9 -0
  114. package/dist/core/configurators/slash/roocode.js +23 -0
  115. package/dist/core/configurators/slash/toml-base.d.ts +10 -0
  116. package/dist/core/configurators/slash/toml-base.js +53 -0
  117. package/dist/core/configurators/slash/windsurf.d.ts +9 -0
  118. package/dist/core/configurators/slash/windsurf.js +23 -0
  119. package/dist/core/converters/json-converter.d.ts +6 -0
  120. package/dist/core/converters/json-converter.js +51 -0
  121. package/dist/core/global-config.d.ts +39 -0
  122. package/dist/core/global-config.js +115 -0
  123. package/dist/core/index.d.ts +2 -0
  124. package/dist/core/index.js +3 -0
  125. package/dist/core/init.d.ts +60 -0
  126. package/dist/core/init.js +861 -0
  127. package/dist/core/list.d.ts +9 -0
  128. package/dist/core/list.js +171 -0
  129. package/dist/core/parsers/change-parser.d.ts +13 -0
  130. package/dist/core/parsers/change-parser.js +193 -0
  131. package/dist/core/parsers/markdown-parser.d.ts +22 -0
  132. package/dist/core/parsers/markdown-parser.js +187 -0
  133. package/dist/core/parsers/requirement-blocks.d.ts +37 -0
  134. package/dist/core/parsers/requirement-blocks.js +201 -0
  135. package/dist/core/project-config.d.ts +34 -0
  136. package/dist/core/project-config.js +79 -0
  137. package/dist/core/schemas/base.schema.d.ts +13 -0
  138. package/dist/core/schemas/base.schema.js +13 -0
  139. package/dist/core/schemas/change.schema.d.ts +73 -0
  140. package/dist/core/schemas/change.schema.js +31 -0
  141. package/dist/core/schemas/index.d.ts +4 -0
  142. package/dist/core/schemas/index.js +4 -0
  143. package/dist/core/schemas/spec.schema.d.ts +18 -0
  144. package/dist/core/schemas/spec.schema.js +15 -0
  145. package/dist/core/skill-discovery.d.ts +24 -0
  146. package/dist/core/skill-discovery.js +153 -0
  147. package/dist/core/specs-apply.d.ts +73 -0
  148. package/dist/core/specs-apply.js +384 -0
  149. package/dist/core/styles/palette.d.ts +7 -0
  150. package/dist/core/styles/palette.js +8 -0
  151. package/dist/core/templates/agents-root-stub.d.ts +2 -0
  152. package/dist/core/templates/agents-root-stub.js +17 -0
  153. package/dist/core/templates/agents-template.d.ts +2 -0
  154. package/dist/core/templates/agents-template.js +706 -0
  155. package/dist/core/templates/claude-template.d.ts +2 -0
  156. package/dist/core/templates/claude-template.js +2 -0
  157. package/dist/core/templates/cline-template.d.ts +2 -0
  158. package/dist/core/templates/cline-template.js +2 -0
  159. package/dist/core/templates/costrict-template.d.ts +2 -0
  160. package/dist/core/templates/costrict-template.js +2 -0
  161. package/dist/core/templates/index.d.ts +17 -0
  162. package/dist/core/templates/index.js +37 -0
  163. package/dist/core/templates/project-template.d.ts +8 -0
  164. package/dist/core/templates/project-template.js +32 -0
  165. package/dist/core/templates/skill-templates.d.ts +103 -0
  166. package/dist/core/templates/skill-templates.js +2131 -0
  167. package/dist/core/templates/slash-command-templates.d.ts +4 -0
  168. package/dist/core/templates/slash-command-templates.js +81 -0
  169. package/dist/core/update.d.ts +4 -0
  170. package/dist/core/update.js +88 -0
  171. package/dist/core/validation/constants.d.ts +34 -0
  172. package/dist/core/validation/constants.js +40 -0
  173. package/dist/core/validation/types.d.ts +18 -0
  174. package/dist/core/validation/types.js +2 -0
  175. package/dist/core/validation/validator.d.ts +33 -0
  176. package/dist/core/validation/validator.js +409 -0
  177. package/dist/core/view.d.ts +8 -0
  178. package/dist/core/view.js +168 -0
  179. package/dist/index.d.ts +3 -0
  180. package/dist/index.js +3 -0
  181. package/dist/utils/change-metadata.d.ts +47 -0
  182. package/dist/utils/change-metadata.js +130 -0
  183. package/dist/utils/change-utils.d.ts +51 -0
  184. package/dist/utils/change-utils.js +100 -0
  185. package/dist/utils/file-system.d.ts +19 -0
  186. package/dist/utils/file-system.js +177 -0
  187. package/dist/utils/index.d.ts +4 -0
  188. package/dist/utils/index.js +5 -0
  189. package/dist/utils/interactive.d.ts +18 -0
  190. package/dist/utils/interactive.js +21 -0
  191. package/dist/utils/item-discovery.d.ts +4 -0
  192. package/dist/utils/item-discovery.js +72 -0
  193. package/dist/utils/match.d.ts +3 -0
  194. package/dist/utils/match.js +22 -0
  195. package/dist/utils/shell-detection.d.ts +20 -0
  196. package/dist/utils/shell-detection.js +41 -0
  197. package/dist/utils/task-progress.d.ts +8 -0
  198. package/dist/utils/task-progress.js +36 -0
  199. package/package.json +81 -0
  200. package/schemas/spec-driven/schema.yaml +205 -0
  201. package/schemas/spec-driven/templates/design.md +19 -0
  202. package/schemas/spec-driven/templates/proposal.md +43 -0
  203. package/schemas/spec-driven/templates/spec.md +8 -0
  204. package/schemas/spec-driven/templates/tasks.md +25 -0
  205. package/schemas/tdd/schema.yaml +213 -0
  206. package/schemas/tdd/templates/docs.md +0 -0
  207. package/schemas/tdd/templates/implementation.md +11 -0
  208. package/schemas/tdd/templates/spec.md +11 -0
  209. package/schemas/tdd/templates/test.md +11 -0
  210. package/scripts/postinstall.js +147 -0
@@ -0,0 +1,130 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import * as yaml from 'yaml';
4
+ import { ChangeMetadataSchema } from '../core/artifact-graph/types.js';
5
+ import { listSchemas } from '../core/artifact-graph/resolver.js';
6
+ const METADATA_FILENAME = '.zhuanspec.yaml';
7
+ /**
8
+ * Error thrown when change metadata validation fails.
9
+ */
10
+ export class ChangeMetadataError extends Error {
11
+ metadataPath;
12
+ cause;
13
+ constructor(message, metadataPath, cause) {
14
+ super(message);
15
+ this.metadataPath = metadataPath;
16
+ this.cause = cause;
17
+ this.name = 'ChangeMetadataError';
18
+ }
19
+ }
20
+ /**
21
+ * Validates that a schema name is valid (exists in available schemas).
22
+ *
23
+ * @param schemaName - The schema name to validate
24
+ * @returns The validated schema name
25
+ * @throws Error if schema is not found
26
+ */
27
+ export function validateSchemaName(schemaName) {
28
+ const availableSchemas = listSchemas();
29
+ if (!availableSchemas.includes(schemaName)) {
30
+ throw new Error(`Unknown schema '${schemaName}'. Available: ${availableSchemas.join(', ')}`);
31
+ }
32
+ return schemaName;
33
+ }
34
+ /**
35
+ * Writes change metadata to .zhuanspec.yaml in the change directory.
36
+ *
37
+ * @param changeDir - The path to the change directory
38
+ * @param metadata - The metadata to write
39
+ * @throws ChangeMetadataError if validation fails or write fails
40
+ */
41
+ export function writeChangeMetadata(changeDir, metadata) {
42
+ const metaPath = path.join(changeDir, METADATA_FILENAME);
43
+ // Validate schema exists
44
+ validateSchemaName(metadata.schema);
45
+ // Validate with Zod
46
+ const parseResult = ChangeMetadataSchema.safeParse(metadata);
47
+ if (!parseResult.success) {
48
+ throw new ChangeMetadataError(`Invalid metadata: ${parseResult.error.message}`, metaPath);
49
+ }
50
+ // Write YAML file
51
+ const content = yaml.stringify(parseResult.data);
52
+ try {
53
+ fs.writeFileSync(metaPath, content, 'utf-8');
54
+ }
55
+ catch (err) {
56
+ const ioError = err instanceof Error ? err : new Error(String(err));
57
+ throw new ChangeMetadataError(`Failed to write metadata: ${ioError.message}`, metaPath, ioError);
58
+ }
59
+ }
60
+ /**
61
+ * Reads change metadata from .zhuanspec.yaml in the change directory.
62
+ *
63
+ * @param changeDir - The path to the change directory
64
+ * @returns The validated metadata, or null if no metadata file exists
65
+ * @throws ChangeMetadataError if the file exists but is invalid
66
+ */
67
+ export function readChangeMetadata(changeDir) {
68
+ const metaPath = path.join(changeDir, METADATA_FILENAME);
69
+ if (!fs.existsSync(metaPath)) {
70
+ return null;
71
+ }
72
+ let content;
73
+ try {
74
+ content = fs.readFileSync(metaPath, 'utf-8');
75
+ }
76
+ catch (err) {
77
+ const ioError = err instanceof Error ? err : new Error(String(err));
78
+ throw new ChangeMetadataError(`Failed to read metadata: ${ioError.message}`, metaPath, ioError);
79
+ }
80
+ let parsed;
81
+ try {
82
+ parsed = yaml.parse(content);
83
+ }
84
+ catch (err) {
85
+ const parseError = err instanceof Error ? err : new Error(String(err));
86
+ throw new ChangeMetadataError(`Invalid YAML in metadata file: ${parseError.message}`, metaPath, parseError);
87
+ }
88
+ // Validate with Zod
89
+ const parseResult = ChangeMetadataSchema.safeParse(parsed);
90
+ if (!parseResult.success) {
91
+ throw new ChangeMetadataError(`Invalid metadata: ${parseResult.error.message}`, metaPath);
92
+ }
93
+ // Validate that the schema exists
94
+ const availableSchemas = listSchemas();
95
+ if (!availableSchemas.includes(parseResult.data.schema)) {
96
+ throw new ChangeMetadataError(`Unknown schema '${parseResult.data.schema}'. Available: ${availableSchemas.join(', ')}`, metaPath);
97
+ }
98
+ return parseResult.data;
99
+ }
100
+ /**
101
+ * Resolves the schema for a change, with explicit override taking precedence.
102
+ *
103
+ * Resolution order:
104
+ * 1. Explicit schema (if provided)
105
+ * 2. Schema from .zhuanspec.yaml metadata (if exists)
106
+ * 3. Default 'spec-driven'
107
+ *
108
+ * @param changeDir - The path to the change directory
109
+ * @param explicitSchema - Optional explicit schema override
110
+ * @returns The resolved schema name
111
+ */
112
+ export function resolveSchemaForChange(changeDir, explicitSchema) {
113
+ // 1. Explicit override wins
114
+ if (explicitSchema) {
115
+ return explicitSchema;
116
+ }
117
+ // 2. Try reading from metadata
118
+ try {
119
+ const metadata = readChangeMetadata(changeDir);
120
+ if (metadata?.schema) {
121
+ return metadata.schema;
122
+ }
123
+ }
124
+ catch {
125
+ // If metadata read fails, fall back to default
126
+ }
127
+ // 3. Default
128
+ return 'spec-driven';
129
+ }
130
+ //# sourceMappingURL=change-metadata.js.map
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Options for creating a change.
3
+ */
4
+ export interface CreateChangeOptions {
5
+ /** The workflow schema to use (default: 'spec-driven') */
6
+ schema?: string;
7
+ }
8
+ /**
9
+ * Result of validating a change name.
10
+ */
11
+ export interface ValidationResult {
12
+ valid: boolean;
13
+ error?: string;
14
+ }
15
+ /**
16
+ * Validates that a change name follows kebab-case conventions.
17
+ *
18
+ * Valid names:
19
+ * - Start with a lowercase letter
20
+ * - Contain only lowercase letters, numbers, and hyphens
21
+ * - Do not start or end with a hyphen
22
+ * - Do not contain consecutive hyphens
23
+ *
24
+ * @param name - The change name to validate
25
+ * @returns Validation result with `valid: true` or `valid: false` with an error message
26
+ *
27
+ * @example
28
+ * validateChangeName('add-auth') // { valid: true }
29
+ * validateChangeName('Add-Auth') // { valid: false, error: '...' }
30
+ */
31
+ export declare function validateChangeName(name: string): ValidationResult;
32
+ /**
33
+ * Creates a new change directory with metadata file.
34
+ *
35
+ * @param projectRoot - The root directory of the project (where `zhuanspec/` lives)
36
+ * @param name - The change name (must be valid kebab-case)
37
+ * @param options - Optional settings for the change
38
+ * @throws Error if the change name is invalid
39
+ * @throws Error if the schema name is invalid
40
+ * @throws Error if the change directory already exists
41
+ *
42
+ * @example
43
+ * // Creates zhuanspec/changes/add-auth/ with default schema
44
+ * await createChange('/path/to/project', 'add-auth')
45
+ *
46
+ * @example
47
+ * // Creates zhuanspec/changes/add-auth/ with TDD schema
48
+ * await createChange('/path/to/project', 'add-auth', { schema: 'tdd' })
49
+ */
50
+ export declare function createChange(projectRoot: string, name: string, options?: CreateChangeOptions): Promise<void>;
51
+ //# sourceMappingURL=change-utils.d.ts.map
@@ -0,0 +1,100 @@
1
+ import path from 'path';
2
+ import { FileSystemUtils } from './file-system.js';
3
+ import { writeChangeMetadata, validateSchemaName } from './change-metadata.js';
4
+ const DEFAULT_SCHEMA = 'spec-driven';
5
+ /**
6
+ * Validates that a change name follows kebab-case conventions.
7
+ *
8
+ * Valid names:
9
+ * - Start with a lowercase letter
10
+ * - Contain only lowercase letters, numbers, and hyphens
11
+ * - Do not start or end with a hyphen
12
+ * - Do not contain consecutive hyphens
13
+ *
14
+ * @param name - The change name to validate
15
+ * @returns Validation result with `valid: true` or `valid: false` with an error message
16
+ *
17
+ * @example
18
+ * validateChangeName('add-auth') // { valid: true }
19
+ * validateChangeName('Add-Auth') // { valid: false, error: '...' }
20
+ */
21
+ export function validateChangeName(name) {
22
+ // Pattern: starts with lowercase letter, followed by lowercase letters/numbers,
23
+ // optionally followed by hyphen + lowercase letters/numbers (repeatable)
24
+ const kebabCasePattern = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
25
+ if (!name) {
26
+ return { valid: false, error: 'Change name cannot be empty' };
27
+ }
28
+ if (!kebabCasePattern.test(name)) {
29
+ // Provide specific error messages for common mistakes
30
+ if (/[A-Z]/.test(name)) {
31
+ return { valid: false, error: 'Change name must be lowercase (use kebab-case)' };
32
+ }
33
+ if (/\s/.test(name)) {
34
+ return { valid: false, error: 'Change name cannot contain spaces (use hyphens instead)' };
35
+ }
36
+ if (/_/.test(name)) {
37
+ return { valid: false, error: 'Change name cannot contain underscores (use hyphens instead)' };
38
+ }
39
+ if (name.startsWith('-')) {
40
+ return { valid: false, error: 'Change name cannot start with a hyphen' };
41
+ }
42
+ if (name.endsWith('-')) {
43
+ return { valid: false, error: 'Change name cannot end with a hyphen' };
44
+ }
45
+ if (/--/.test(name)) {
46
+ return { valid: false, error: 'Change name cannot contain consecutive hyphens' };
47
+ }
48
+ if (/[^a-z0-9-]/.test(name)) {
49
+ return { valid: false, error: 'Change name can only contain lowercase letters, numbers, and hyphens' };
50
+ }
51
+ if (/^[0-9]/.test(name)) {
52
+ return { valid: false, error: 'Change name must start with a letter' };
53
+ }
54
+ return { valid: false, error: 'Change name must follow kebab-case convention (e.g., add-auth, refactor-db)' };
55
+ }
56
+ return { valid: true };
57
+ }
58
+ /**
59
+ * Creates a new change directory with metadata file.
60
+ *
61
+ * @param projectRoot - The root directory of the project (where `zhuanspec/` lives)
62
+ * @param name - The change name (must be valid kebab-case)
63
+ * @param options - Optional settings for the change
64
+ * @throws Error if the change name is invalid
65
+ * @throws Error if the schema name is invalid
66
+ * @throws Error if the change directory already exists
67
+ *
68
+ * @example
69
+ * // Creates zhuanspec/changes/add-auth/ with default schema
70
+ * await createChange('/path/to/project', 'add-auth')
71
+ *
72
+ * @example
73
+ * // Creates zhuanspec/changes/add-auth/ with TDD schema
74
+ * await createChange('/path/to/project', 'add-auth', { schema: 'tdd' })
75
+ */
76
+ export async function createChange(projectRoot, name, options = {}) {
77
+ // Validate the name first
78
+ const validation = validateChangeName(name);
79
+ if (!validation.valid) {
80
+ throw new Error(validation.error);
81
+ }
82
+ // Determine schema (validate if provided)
83
+ const schemaName = options.schema ?? DEFAULT_SCHEMA;
84
+ validateSchemaName(schemaName);
85
+ // Build the change directory path
86
+ const changeDir = path.join(projectRoot, 'zhuanspec', 'changes', name);
87
+ // Check if change already exists
88
+ if (await FileSystemUtils.directoryExists(changeDir)) {
89
+ throw new Error(`Change '${name}' already exists at ${changeDir}`);
90
+ }
91
+ // Create the directory (including parent directories if needed)
92
+ await FileSystemUtils.createDirectory(changeDir);
93
+ // Write metadata file with schema and creation date
94
+ const today = new Date().toISOString().split('T')[0];
95
+ writeChangeMetadata(changeDir, {
96
+ schema: schemaName,
97
+ created: today,
98
+ });
99
+ }
100
+ //# sourceMappingURL=change-utils.js.map
@@ -0,0 +1,19 @@
1
+ export declare class FileSystemUtils {
2
+ /**
3
+ * Converts a path to use forward slashes (POSIX style).
4
+ * Essential for cross-platform compatibility with glob libraries like fast-glob.
5
+ */
6
+ static toPosixPath(p: string): string;
7
+ private static isWindowsBasePath;
8
+ private static normalizeSegments;
9
+ static joinPath(basePath: string, ...segments: string[]): string;
10
+ static createDirectory(dirPath: string): Promise<void>;
11
+ static fileExists(filePath: string): Promise<boolean>;
12
+ static canWriteFile(filePath: string): Promise<boolean>;
13
+ static directoryExists(dirPath: string): Promise<boolean>;
14
+ static writeFile(filePath: string, content: string): Promise<void>;
15
+ static readFile(filePath: string): Promise<string>;
16
+ static updateFileWithMarkers(filePath: string, content: string, startMarker: string, endMarker: string): Promise<void>;
17
+ static ensureWritePermissions(dirPath: string): Promise<boolean>;
18
+ }
19
+ //# sourceMappingURL=file-system.d.ts.map
@@ -0,0 +1,177 @@
1
+ import { promises as fs, constants as fsConstants } from 'fs';
2
+ import path from 'path';
3
+ function isMarkerOnOwnLine(content, markerIndex, markerLength) {
4
+ let leftIndex = markerIndex - 1;
5
+ while (leftIndex >= 0 && content[leftIndex] !== '\n') {
6
+ const char = content[leftIndex];
7
+ if (char !== ' ' && char !== '\t' && char !== '\r') {
8
+ return false;
9
+ }
10
+ leftIndex--;
11
+ }
12
+ let rightIndex = markerIndex + markerLength;
13
+ while (rightIndex < content.length && content[rightIndex] !== '\n') {
14
+ const char = content[rightIndex];
15
+ if (char !== ' ' && char !== '\t' && char !== '\r') {
16
+ return false;
17
+ }
18
+ rightIndex++;
19
+ }
20
+ return true;
21
+ }
22
+ function findMarkerIndex(content, marker, fromIndex = 0) {
23
+ let currentIndex = content.indexOf(marker, fromIndex);
24
+ while (currentIndex !== -1) {
25
+ if (isMarkerOnOwnLine(content, currentIndex, marker.length)) {
26
+ return currentIndex;
27
+ }
28
+ currentIndex = content.indexOf(marker, currentIndex + marker.length);
29
+ }
30
+ return -1;
31
+ }
32
+ export class FileSystemUtils {
33
+ /**
34
+ * Converts a path to use forward slashes (POSIX style).
35
+ * Essential for cross-platform compatibility with glob libraries like fast-glob.
36
+ */
37
+ static toPosixPath(p) {
38
+ return p.replace(/\\/g, '/');
39
+ }
40
+ static isWindowsBasePath(basePath) {
41
+ return /^[A-Za-z]:[\\/]/.test(basePath) || basePath.startsWith('\\');
42
+ }
43
+ static normalizeSegments(segments) {
44
+ return segments
45
+ .flatMap((segment) => segment.split(/[\\/]+/u))
46
+ .filter((part) => part.length > 0);
47
+ }
48
+ static joinPath(basePath, ...segments) {
49
+ const normalizedSegments = this.normalizeSegments(segments);
50
+ if (this.isWindowsBasePath(basePath)) {
51
+ const normalizedBasePath = path.win32.normalize(basePath);
52
+ return normalizedSegments.length
53
+ ? path.win32.join(normalizedBasePath, ...normalizedSegments)
54
+ : normalizedBasePath;
55
+ }
56
+ const posixBasePath = basePath.replace(/\\/g, '/');
57
+ return normalizedSegments.length
58
+ ? path.posix.join(posixBasePath, ...normalizedSegments)
59
+ : path.posix.normalize(posixBasePath);
60
+ }
61
+ static async createDirectory(dirPath) {
62
+ await fs.mkdir(dirPath, { recursive: true });
63
+ }
64
+ static async fileExists(filePath) {
65
+ try {
66
+ await fs.access(filePath);
67
+ return true;
68
+ }
69
+ catch (error) {
70
+ if (error.code !== 'ENOENT') {
71
+ console.debug(`Unable to check if file exists at ${filePath}: ${error.message}`);
72
+ }
73
+ return false;
74
+ }
75
+ }
76
+ static async canWriteFile(filePath) {
77
+ try {
78
+ const stats = await fs.stat(filePath);
79
+ if (!stats.isFile()) {
80
+ return true;
81
+ }
82
+ // On Windows, stats.mode doesn't reliably indicate write permissions.
83
+ // Use fs.access with W_OK to check actual write permissions cross-platform.
84
+ try {
85
+ await fs.access(filePath, fsConstants.W_OK);
86
+ return true;
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ }
92
+ catch (error) {
93
+ if (error.code === 'ENOENT') {
94
+ // File doesn't exist; check if we can write to the parent directory
95
+ const parentDir = path.dirname(filePath);
96
+ try {
97
+ await fs.access(parentDir, fsConstants.W_OK);
98
+ return true;
99
+ }
100
+ catch {
101
+ return false;
102
+ }
103
+ }
104
+ console.debug(`Unable to determine write permissions for ${filePath}: ${error.message}`);
105
+ return false;
106
+ }
107
+ }
108
+ static async directoryExists(dirPath) {
109
+ try {
110
+ const stats = await fs.stat(dirPath);
111
+ return stats.isDirectory();
112
+ }
113
+ catch (error) {
114
+ if (error.code !== 'ENOENT') {
115
+ console.debug(`Unable to check if directory exists at ${dirPath}: ${error.message}`);
116
+ }
117
+ return false;
118
+ }
119
+ }
120
+ static async writeFile(filePath, content) {
121
+ const dir = path.dirname(filePath);
122
+ await this.createDirectory(dir);
123
+ await fs.writeFile(filePath, content, 'utf-8');
124
+ }
125
+ static async readFile(filePath) {
126
+ return await fs.readFile(filePath, 'utf-8');
127
+ }
128
+ static async updateFileWithMarkers(filePath, content, startMarker, endMarker) {
129
+ let existingContent = '';
130
+ if (await this.fileExists(filePath)) {
131
+ existingContent = await this.readFile(filePath);
132
+ const startIndex = findMarkerIndex(existingContent, startMarker);
133
+ const endIndex = startIndex !== -1
134
+ ? findMarkerIndex(existingContent, endMarker, startIndex + startMarker.length)
135
+ : findMarkerIndex(existingContent, endMarker);
136
+ if (startIndex !== -1 && endIndex !== -1) {
137
+ if (endIndex < startIndex) {
138
+ throw new Error(`Invalid marker state in ${filePath}. End marker appears before start marker.`);
139
+ }
140
+ const before = existingContent.substring(0, startIndex);
141
+ const after = existingContent.substring(endIndex + endMarker.length);
142
+ existingContent = before + startMarker + '\n' + content + '\n' + endMarker + after;
143
+ }
144
+ else if (startIndex === -1 && endIndex === -1) {
145
+ existingContent = startMarker + '\n' + content + '\n' + endMarker + '\n\n' + existingContent;
146
+ }
147
+ else {
148
+ throw new Error(`Invalid marker state in ${filePath}. Found start: ${startIndex !== -1}, Found end: ${endIndex !== -1}`);
149
+ }
150
+ }
151
+ else {
152
+ existingContent = startMarker + '\n' + content + '\n' + endMarker;
153
+ }
154
+ await this.writeFile(filePath, existingContent);
155
+ }
156
+ static async ensureWritePermissions(dirPath) {
157
+ try {
158
+ // If directory doesn't exist, check parent directory permissions
159
+ if (!await this.directoryExists(dirPath)) {
160
+ const parentDir = path.dirname(dirPath);
161
+ if (!await this.directoryExists(parentDir)) {
162
+ await this.createDirectory(parentDir);
163
+ }
164
+ return await this.ensureWritePermissions(parentDir);
165
+ }
166
+ const testFile = path.join(dirPath, '.zhuanspec-test-' + Date.now());
167
+ await fs.writeFile(testFile, '');
168
+ await fs.unlink(testFile);
169
+ return true;
170
+ }
171
+ catch (error) {
172
+ console.debug(`Insufficient permissions to write to ${dirPath}: ${error.message}`);
173
+ return false;
174
+ }
175
+ }
176
+ }
177
+ //# sourceMappingURL=file-system.js.map
@@ -0,0 +1,4 @@
1
+ export { validateChangeName, createChange } from './change-utils.js';
2
+ export type { ValidationResult, CreateChangeOptions } from './change-utils.js';
3
+ export { readChangeMetadata, writeChangeMetadata, resolveSchemaForChange, validateSchemaName, ChangeMetadataError, } from './change-metadata.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ // Shared utilities
2
+ export { validateChangeName, createChange } from './change-utils.js';
3
+ // Change metadata utilities
4
+ export { readChangeMetadata, writeChangeMetadata, resolveSchemaForChange, validateSchemaName, ChangeMetadataError, } from './change-metadata.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,18 @@
1
+ export type InteractiveOptions = {
2
+ /**
3
+ * Explicit "disable prompts" flag passed by internal callers.
4
+ */
5
+ noInteractive?: boolean;
6
+ /**
7
+ * Commander-style negated option: `--no-interactive` sets this to false.
8
+ */
9
+ interactive?: boolean;
10
+ };
11
+ /**
12
+ * Resolves whether non-interactive mode is requested.
13
+ * Handles both explicit `noInteractive: true` and Commander.js style `interactive: false`.
14
+ * Use this helper instead of manually checking options.noInteractive to avoid bugs.
15
+ */
16
+ export declare function resolveNoInteractive(value?: boolean | InteractiveOptions): boolean;
17
+ export declare function isInteractive(value?: boolean | InteractiveOptions): boolean;
18
+ //# sourceMappingURL=interactive.d.ts.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Resolves whether non-interactive mode is requested.
3
+ * Handles both explicit `noInteractive: true` and Commander.js style `interactive: false`.
4
+ * Use this helper instead of manually checking options.noInteractive to avoid bugs.
5
+ */
6
+ export function resolveNoInteractive(value) {
7
+ if (typeof value === 'boolean')
8
+ return value;
9
+ return value?.noInteractive === true || value?.interactive === false;
10
+ }
11
+ export function isInteractive(value) {
12
+ if (resolveNoInteractive(value))
13
+ return false;
14
+ if (process.env.OPEN_SPEC_INTERACTIVE === '0')
15
+ return false;
16
+ // Respect the standard CI environment variable (set by GitHub Actions, GitLab CI, Travis, etc.)
17
+ if ('CI' in process.env)
18
+ return false;
19
+ return !!process.stdin.isTTY;
20
+ }
21
+ //# sourceMappingURL=interactive.js.map
@@ -0,0 +1,4 @@
1
+ export declare function getActiveChangeIds(root?: string): Promise<string[]>;
2
+ export declare function getSpecIds(root?: string): Promise<string[]>;
3
+ export declare function getArchivedChangeIds(root?: string): Promise<string[]>;
4
+ //# sourceMappingURL=item-discovery.d.ts.map
@@ -0,0 +1,72 @@
1
+ import { promises as fs } from 'fs';
2
+ import path from 'path';
3
+ export async function getActiveChangeIds(root = process.cwd()) {
4
+ const changesPath = path.join(root, 'zhuanspec', 'changes');
5
+ try {
6
+ const entries = await fs.readdir(changesPath, { withFileTypes: true });
7
+ const result = [];
8
+ for (const entry of entries) {
9
+ if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'archive')
10
+ continue;
11
+ const proposalPath = path.join(changesPath, entry.name, 'proposal.md');
12
+ try {
13
+ await fs.access(proposalPath);
14
+ result.push(entry.name);
15
+ }
16
+ catch {
17
+ // skip directories without proposal.md
18
+ }
19
+ }
20
+ return result.sort();
21
+ }
22
+ catch {
23
+ return [];
24
+ }
25
+ }
26
+ export async function getSpecIds(root = process.cwd()) {
27
+ const specsPath = path.join(root, 'zhuanspec', 'specs');
28
+ const result = [];
29
+ try {
30
+ const entries = await fs.readdir(specsPath, { withFileTypes: true });
31
+ for (const entry of entries) {
32
+ if (!entry.isDirectory() || entry.name.startsWith('.'))
33
+ continue;
34
+ const specFile = path.join(specsPath, entry.name, 'spec.md');
35
+ try {
36
+ await fs.access(specFile);
37
+ result.push(entry.name);
38
+ }
39
+ catch {
40
+ // ignore
41
+ }
42
+ }
43
+ }
44
+ catch {
45
+ // ignore
46
+ }
47
+ return result.sort();
48
+ }
49
+ export async function getArchivedChangeIds(root = process.cwd()) {
50
+ const archivePath = path.join(root, 'zhuanspec', 'changes', 'archive');
51
+ try {
52
+ const entries = await fs.readdir(archivePath, { withFileTypes: true });
53
+ const result = [];
54
+ for (const entry of entries) {
55
+ if (!entry.isDirectory() || entry.name.startsWith('.'))
56
+ continue;
57
+ const proposalPath = path.join(archivePath, entry.name, 'proposal.md');
58
+ try {
59
+ await fs.access(proposalPath);
60
+ result.push(entry.name);
61
+ }
62
+ catch {
63
+ // skip directories without proposal.md
64
+ }
65
+ }
66
+ return result.sort();
67
+ }
68
+ catch {
69
+ return [];
70
+ }
71
+ }
72
+ //# sourceMappingURL=item-discovery.js.map
@@ -0,0 +1,3 @@
1
+ export declare function nearestMatches(input: string, candidates: string[], max?: number): string[];
2
+ export declare function levenshtein(a: string, b: string): number;
3
+ //# sourceMappingURL=match.d.ts.map
@@ -0,0 +1,22 @@
1
+ export function nearestMatches(input, candidates, max = 5) {
2
+ const scored = candidates.map(candidate => ({ candidate, distance: levenshtein(input, candidate) }));
3
+ scored.sort((a, b) => a.distance - b.distance);
4
+ return scored.slice(0, max).map(s => s.candidate);
5
+ }
6
+ export function levenshtein(a, b) {
7
+ const m = a.length;
8
+ const n = b.length;
9
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
10
+ for (let i = 0; i <= m; i++)
11
+ dp[i][0] = i;
12
+ for (let j = 0; j <= n; j++)
13
+ dp[0][j] = j;
14
+ for (let i = 1; i <= m; i++) {
15
+ for (let j = 1; j <= n; j++) {
16
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
17
+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
18
+ }
19
+ }
20
+ return dp[m][n];
21
+ }
22
+ //# sourceMappingURL=match.js.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Supported shell types for completion generation
3
+ */
4
+ export type SupportedShell = 'zsh' | 'bash' | 'fish' | 'powershell';
5
+ /**
6
+ * Result of shell detection
7
+ */
8
+ export interface ShellDetectionResult {
9
+ /** The detected shell if supported, otherwise undefined */
10
+ shell: SupportedShell | undefined;
11
+ /** The raw shell name detected (even if unsupported), or undefined if nothing detected */
12
+ detected: string | undefined;
13
+ }
14
+ /**
15
+ * Detects the current user's shell based on environment variables
16
+ *
17
+ * @returns Detection result with supported shell and raw detected name
18
+ */
19
+ export declare function detectShell(): ShellDetectionResult;
20
+ //# sourceMappingURL=shell-detection.d.ts.map