@ai-dev-orchestrator/specification 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AI Dev Orchestrator Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # @ai-dev-orchestrator/specification
2
+
3
+ Specification validation, merging, and versioning for canonical project specifications. Ensures specifications conform to schema rules, resolves merge conflicts between versions, and manages the version chain.
4
+
5
+ ## Architecture Layer
6
+
7
+ **Domain** -- defines the specification model and its invariants.
8
+
9
+ ## Workspace Dependencies
10
+
11
+ - `@ai-dev-orchestrator/ports`
12
+ - `@ai-dev-orchestrator/schemas`
13
+
14
+ ## Structure
15
+
16
+ ```
17
+ src/
18
+ domain/
19
+ __tests__/
20
+ infrastructure/
21
+ __tests__/
22
+ ```
23
+
24
+ ## Key Exports
25
+
26
+ ### Domain
27
+
28
+ - `COMPLETENESS_WEIGHTS` -- weights for specification completeness scoring
29
+ - `createSpecificationId` -- generates unique specification identifiers
30
+ - **Errors:** `SpecificationMergeConflictError`, `SpecificationSchemaError`, `SpecificationSemanticError`, `SpecificationVersionChainError`
31
+
32
+ ### Infrastructure
33
+
34
+ - `DefaultSpecificationValidator` -- validates specifications against schema and semantic rules
35
+ - `DefaultSpecificationMerger` -- merges specification versions with conflict detection
36
+ - `serializeSpecification`, `deserializeSpecification` -- serialization helpers
37
+ - `createNextVersion` -- produces the next version in a specification chain
@@ -0,0 +1,35 @@
1
+ import { NonRecoverableErrorBase } from '@ai-dev-orchestrator/ports';
2
+ import type { MergeConflict } from '@ai-dev-orchestrator/schemas';
3
+ /** Thrown when a specification fails structural validation. */
4
+ export declare class SpecificationSchemaError extends NonRecoverableErrorBase {
5
+ readonly field: string;
6
+ readonly violations: readonly {
7
+ readonly path: string;
8
+ readonly message: string;
9
+ }[];
10
+ readonly code = "SPEC_SCHEMA_ERROR";
11
+ constructor(field: string, violations: readonly {
12
+ readonly path: string;
13
+ readonly message: string;
14
+ }[]);
15
+ }
16
+ /** Thrown when a specification has semantic inconsistencies. */
17
+ export declare class SpecificationSemanticError extends NonRecoverableErrorBase {
18
+ readonly field: string;
19
+ readonly detail: string;
20
+ readonly code = "SPEC_SEMANTIC_ERROR";
21
+ constructor(field: string, detail: string);
22
+ }
23
+ /** Thrown when specification merge produces unresolvable conflicts. */
24
+ export declare class SpecificationMergeConflictError extends NonRecoverableErrorBase {
25
+ readonly conflicts: readonly MergeConflict[];
26
+ readonly code = "SPEC_MERGE_CONFLICT";
27
+ constructor(conflicts: readonly MergeConflict[]);
28
+ }
29
+ /** Thrown when a specification version chain is broken. */
30
+ export declare class SpecificationVersionChainError extends NonRecoverableErrorBase {
31
+ readonly specId: string;
32
+ readonly missingVersion: string;
33
+ readonly code = "SPEC_VERSION_CHAIN_ERROR";
34
+ constructor(specId: string, missingVersion: string);
35
+ }
@@ -0,0 +1,44 @@
1
+ import { NonRecoverableErrorBase } from '@ai-dev-orchestrator/ports';
2
+ /** Thrown when a specification fails structural validation. */
3
+ export class SpecificationSchemaError extends NonRecoverableErrorBase {
4
+ field;
5
+ violations;
6
+ code = 'SPEC_SCHEMA_ERROR';
7
+ constructor(field, violations) {
8
+ const details = violations.map((v) => `${v.path}: ${v.message}`).join('; ');
9
+ super(`Specification schema violation in "${field}": ${details}`);
10
+ this.field = field;
11
+ this.violations = violations;
12
+ }
13
+ }
14
+ /** Thrown when a specification has semantic inconsistencies. */
15
+ export class SpecificationSemanticError extends NonRecoverableErrorBase {
16
+ field;
17
+ detail;
18
+ code = 'SPEC_SEMANTIC_ERROR';
19
+ constructor(field, detail) {
20
+ super(`Semantic error in "${field}": ${detail}`);
21
+ this.field = field;
22
+ this.detail = detail;
23
+ }
24
+ }
25
+ /** Thrown when specification merge produces unresolvable conflicts. */
26
+ export class SpecificationMergeConflictError extends NonRecoverableErrorBase {
27
+ conflicts;
28
+ code = 'SPEC_MERGE_CONFLICT';
29
+ constructor(conflicts) {
30
+ super(`Merge produced ${String(conflicts.length)} unresolvable conflict(s): ${conflicts.map((c) => c.field).join(', ')}`);
31
+ this.conflicts = conflicts;
32
+ }
33
+ }
34
+ /** Thrown when a specification version chain is broken. */
35
+ export class SpecificationVersionChainError extends NonRecoverableErrorBase {
36
+ specId;
37
+ missingVersion;
38
+ code = 'SPEC_VERSION_CHAIN_ERROR';
39
+ constructor(specId, missingVersion) {
40
+ super(`Version chain broken for specification "${specId}": previous version "${missingVersion}" not found`);
41
+ this.specId = specId;
42
+ this.missingVersion = missingVersion;
43
+ }
44
+ }
@@ -0,0 +1,3 @@
1
+ export { createSpecificationId } from './types';
2
+ export { COMPLETENESS_WEIGHTS } from '@ai-dev-orchestrator/schemas';
3
+ export { SpecificationMergeConflictError, SpecificationSchemaError, SpecificationSemanticError, SpecificationVersionChainError, } from './errors';
@@ -0,0 +1,3 @@
1
+ export { createSpecificationId } from './types';
2
+ export { COMPLETENESS_WEIGHTS } from '@ai-dev-orchestrator/schemas';
3
+ export { SpecificationMergeConflictError, SpecificationSchemaError, SpecificationSemanticError, SpecificationVersionChainError, } from './errors';
@@ -0,0 +1,2 @@
1
+ import type { SpecificationId } from '@ai-dev-orchestrator/schemas';
2
+ export declare function createSpecificationId(value?: string): SpecificationId;
@@ -0,0 +1,4 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ export function createSpecificationId(value) {
3
+ return (value ?? randomUUID());
4
+ }
@@ -0,0 +1,2 @@
1
+ export { COMPLETENESS_WEIGHTS, createSpecificationId, SpecificationMergeConflictError, SpecificationSchemaError, SpecificationSemanticError, SpecificationVersionChainError, } from './domain/index';
2
+ export { DefaultSpecificationValidator, DefaultSpecificationMerger, serializeSpecification, deserializeSpecification, createNextVersion, } from './infrastructure/index';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ // Domain — Canonical Specification
2
+ export { COMPLETENESS_WEIGHTS, createSpecificationId, SpecificationMergeConflictError, SpecificationSchemaError, SpecificationSemanticError, SpecificationVersionChainError, } from './domain/index';
3
+ // Infrastructure — Canonical Specification
4
+ export { DefaultSpecificationValidator, DefaultSpecificationMerger, serializeSpecification, deserializeSpecification, createNextVersion, } from './infrastructure/index';
@@ -0,0 +1,5 @@
1
+ import type { SpecificationMerger } from '@ai-dev-orchestrator/ports';
2
+ import type { CanonicalSpecification, MergeResult, MergeStrategy } from '@ai-dev-orchestrator/schemas';
3
+ export declare class DefaultSpecificationMerger implements SpecificationMerger {
4
+ merge(specs: readonly CanonicalSpecification[], strategy: MergeStrategy): MergeResult;
5
+ }
@@ -0,0 +1,105 @@
1
+ import { createSpecificationId } from '../domain/types';
2
+ export class DefaultSpecificationMerger {
3
+ merge(specs, strategy) {
4
+ if (specs.length === 0) {
5
+ const now = new Date().toISOString();
6
+ return {
7
+ merged: {
8
+ id: createSpecificationId(),
9
+ version: 1,
10
+ title: '',
11
+ businessGoal: '',
12
+ stakeholders: [],
13
+ assumptions: [],
14
+ constraints: [],
15
+ functionalRequirements: [],
16
+ nonFunctionalRequirements: [],
17
+ acceptanceCriteria: [],
18
+ risks: [],
19
+ dependencies: [],
20
+ definitionOfDone: [],
21
+ sources: [],
22
+ createdAt: now,
23
+ updatedAt: now,
24
+ },
25
+ conflicts: [],
26
+ };
27
+ }
28
+ if (specs.length === 1) {
29
+ return { merged: { ...specs[0] }, conflicts: [] };
30
+ }
31
+ const conflicts = [];
32
+ const now = new Date().toISOString();
33
+ const resolveScalar = (field, values, getter) => {
34
+ const unique = [...new Set(values.map(getter).filter((v) => v.length > 0))];
35
+ if (unique.length <= 1) {
36
+ return unique[0] ?? '';
37
+ }
38
+ if (strategy.scalarConflict === 'flag-conflict') {
39
+ conflicts.push({
40
+ field,
41
+ values: unique.map((v, i) => ({
42
+ source: values[i]?.id ?? `spec-${String(i)}`,
43
+ value: v,
44
+ })),
45
+ resolution: 'flagged',
46
+ });
47
+ return unique[0];
48
+ }
49
+ const resolved = strategy.scalarConflict === 'last-wins' ? unique[unique.length - 1] : unique[0];
50
+ conflicts.push({
51
+ field,
52
+ values: unique.map((v, i) => ({ source: values[i]?.id ?? `spec-${String(i)}`, value: v })),
53
+ resolution: 'auto-resolved',
54
+ resolvedValue: resolved,
55
+ });
56
+ return resolved;
57
+ };
58
+ const mergeArrays = (arrays) => {
59
+ if (strategy.arrayMerge === 'concatenate') {
60
+ return arrays.flat();
61
+ }
62
+ if (!strategy.deduplication) {
63
+ return arrays.flat();
64
+ }
65
+ const seen = new Set();
66
+ const result = [];
67
+ for (const arr of arrays) {
68
+ for (const item of arr) {
69
+ if (!seen.has(item.id)) {
70
+ seen.add(item.id);
71
+ result.push(item);
72
+ }
73
+ }
74
+ }
75
+ return result;
76
+ };
77
+ const mergeStringArrays = (arrays) => {
78
+ if (strategy.arrayMerge === 'concatenate') {
79
+ return arrays.flat();
80
+ }
81
+ return strategy.deduplication ? [...new Set(arrays.flat())] : arrays.flat();
82
+ };
83
+ const title = resolveScalar('title', specs, (s) => s.title);
84
+ const businessGoal = resolveScalar('businessGoal', specs, (s) => s.businessGoal);
85
+ const merged = {
86
+ id: createSpecificationId(),
87
+ version: 1,
88
+ title,
89
+ businessGoal,
90
+ stakeholders: specs.flatMap((s) => s.stakeholders),
91
+ assumptions: mergeArrays(specs.map((s) => s.assumptions)),
92
+ constraints: mergeArrays(specs.map((s) => s.constraints)),
93
+ functionalRequirements: mergeArrays(specs.map((s) => s.functionalRequirements)),
94
+ nonFunctionalRequirements: mergeArrays(specs.map((s) => s.nonFunctionalRequirements)),
95
+ acceptanceCriteria: mergeArrays(specs.map((s) => s.acceptanceCriteria)),
96
+ risks: mergeArrays(specs.map((s) => s.risks)),
97
+ dependencies: mergeArrays(specs.map((s) => s.dependencies)),
98
+ definitionOfDone: mergeStringArrays(specs.map((s) => s.definitionOfDone)),
99
+ sources: specs.flatMap((s) => s.sources),
100
+ createdAt: now,
101
+ updatedAt: now,
102
+ };
103
+ return { merged, conflicts };
104
+ }
105
+ }
@@ -0,0 +1,7 @@
1
+ import type { SpecificationValidator } from '@ai-dev-orchestrator/ports';
2
+ import type { CanonicalSpecification, CompletenessResult, SpecificationValidationResult } from '@ai-dev-orchestrator/schemas';
3
+ export declare class DefaultSpecificationValidator implements SpecificationValidator {
4
+ validateStructure(spec: CanonicalSpecification): SpecificationValidationResult;
5
+ validateSemantics(spec: CanonicalSpecification): SpecificationValidationResult;
6
+ validateCompleteness(spec: CanonicalSpecification): CompletenessResult;
7
+ }
@@ -0,0 +1,245 @@
1
+ import { COMPLETENESS_WEIGHTS } from '@ai-dev-orchestrator/schemas';
2
+ import { z } from 'zod';
3
+ const structureSchema = z
4
+ .object({
5
+ id: z.string().min(1),
6
+ version: z.number().min(1),
7
+ title: z.string().min(1),
8
+ businessGoal: z.string().min(1),
9
+ stakeholders: z.array(z.unknown()),
10
+ assumptions: z.array(z.unknown()),
11
+ constraints: z.array(z.unknown()),
12
+ functionalRequirements: z.array(z.unknown()),
13
+ nonFunctionalRequirements: z.array(z.unknown()),
14
+ acceptanceCriteria: z.array(z.unknown()),
15
+ risks: z.array(z.unknown()),
16
+ dependencies: z.array(z.unknown()),
17
+ definitionOfDone: z.array(z.unknown()),
18
+ createdAt: z.string().min(1),
19
+ updatedAt: z.string().min(1),
20
+ })
21
+ .loose();
22
+ const STRUCTURE_RULES = {
23
+ id: { message: 'Specification id is required', rule: 'required' },
24
+ version: { message: 'Version must be a positive integer', rule: 'positive-integer' },
25
+ title: { message: 'Title is required', rule: 'required' },
26
+ businessGoal: { message: 'Business goal is required', rule: 'required' },
27
+ stakeholders: { message: 'Stakeholders must be an array', rule: 'type' },
28
+ assumptions: { message: 'Assumptions must be an array', rule: 'type' },
29
+ constraints: { message: 'Constraints must be an array', rule: 'type' },
30
+ functionalRequirements: {
31
+ message: 'Functional requirements must be an array',
32
+ rule: 'type',
33
+ },
34
+ nonFunctionalRequirements: {
35
+ message: 'Non-functional requirements must be an array',
36
+ rule: 'type',
37
+ },
38
+ acceptanceCriteria: { message: 'Acceptance criteria must be an array', rule: 'type' },
39
+ risks: { message: 'Risks must be an array', rule: 'type' },
40
+ dependencies: { message: 'Dependencies must be an array', rule: 'type' },
41
+ definitionOfDone: { message: 'Definition of done must be an array', rule: 'type' },
42
+ createdAt: { message: 'Created timestamp is required', rule: 'required' },
43
+ updatedAt: { message: 'Updated timestamp is required', rule: 'required' },
44
+ };
45
+ export class DefaultSpecificationValidator {
46
+ validateStructure(spec) {
47
+ const errors = [];
48
+ const warnings = [];
49
+ const result = structureSchema.safeParse(spec);
50
+ if (!result.success) {
51
+ for (const zi of result.error.issues) {
52
+ const field = String(zi.path[0] ?? '');
53
+ const mapped = STRUCTURE_RULES[field];
54
+ errors.push({ field, message: mapped.message, rule: mapped.rule });
55
+ }
56
+ }
57
+ if (spec.functionalRequirements.length === 0) {
58
+ warnings.push({
59
+ field: 'functionalRequirements',
60
+ message: 'No functional requirements defined',
61
+ suggestion: 'Add at least one "must" priority functional requirement',
62
+ });
63
+ }
64
+ return { valid: errors.length === 0, errors, warnings };
65
+ }
66
+ validateSemantics(spec) {
67
+ const errors = [];
68
+ const warnings = [];
69
+ const frIds = new Set();
70
+ for (const fr of spec.functionalRequirements) {
71
+ if (frIds.has(fr.id)) {
72
+ errors.push({
73
+ field: 'functionalRequirements',
74
+ message: `Duplicate functional requirement ID: ${fr.id}`,
75
+ rule: 'unique-id',
76
+ });
77
+ }
78
+ frIds.add(fr.id);
79
+ }
80
+ const nfrIds = new Set();
81
+ for (const nfr of spec.nonFunctionalRequirements) {
82
+ if (nfrIds.has(nfr.id)) {
83
+ errors.push({
84
+ field: 'nonFunctionalRequirements',
85
+ message: `Duplicate non-functional requirement ID: ${nfr.id}`,
86
+ rule: 'unique-id',
87
+ });
88
+ }
89
+ nfrIds.add(nfr.id);
90
+ }
91
+ const acIds = new Set();
92
+ for (const ac of spec.acceptanceCriteria) {
93
+ if (acIds.has(ac.id)) {
94
+ errors.push({
95
+ field: 'acceptanceCriteria',
96
+ message: `Duplicate acceptance criterion ID: ${ac.id}`,
97
+ rule: 'unique-id',
98
+ });
99
+ }
100
+ acIds.add(ac.id);
101
+ for (const reqId of ac.requirementIds) {
102
+ if (!frIds.has(reqId)) {
103
+ errors.push({
104
+ field: 'acceptanceCriteria',
105
+ message: `Acceptance criterion ${ac.id} references non-existent requirement ${reqId}`,
106
+ rule: 'valid-reference',
107
+ });
108
+ }
109
+ }
110
+ }
111
+ const riskIds = new Set();
112
+ for (const risk of spec.risks) {
113
+ if (riskIds.has(risk.id)) {
114
+ errors.push({
115
+ field: 'risks',
116
+ message: `Duplicate risk ID: ${risk.id}`,
117
+ rule: 'unique-id',
118
+ });
119
+ }
120
+ riskIds.add(risk.id);
121
+ }
122
+ const depIds = new Set();
123
+ for (const dep of spec.dependencies) {
124
+ if (depIds.has(dep.id)) {
125
+ errors.push({
126
+ field: 'dependencies',
127
+ message: `Duplicate dependency ID: ${dep.id}`,
128
+ rule: 'unique-id',
129
+ });
130
+ }
131
+ depIds.add(dep.id);
132
+ }
133
+ const assumptionIds = new Set();
134
+ for (const a of spec.assumptions) {
135
+ if (assumptionIds.has(a.id)) {
136
+ errors.push({
137
+ field: 'assumptions',
138
+ message: `Duplicate assumption ID: ${a.id}`,
139
+ rule: 'unique-id',
140
+ });
141
+ }
142
+ assumptionIds.add(a.id);
143
+ }
144
+ const constraintIds = new Set();
145
+ for (const c of spec.constraints) {
146
+ if (constraintIds.has(c.id)) {
147
+ errors.push({
148
+ field: 'constraints',
149
+ message: `Duplicate constraint ID: ${c.id}`,
150
+ rule: 'unique-id',
151
+ });
152
+ }
153
+ constraintIds.add(c.id);
154
+ }
155
+ for (const fr of spec.functionalRequirements) {
156
+ if (fr.dependencies) {
157
+ for (const depId of fr.dependencies) {
158
+ if (depId === fr.id) {
159
+ errors.push({
160
+ field: 'functionalRequirements',
161
+ message: `Requirement ${fr.id} references itself as a dependency`,
162
+ rule: 'no-self-reference',
163
+ });
164
+ }
165
+ if (!frIds.has(depId)) {
166
+ warnings.push({
167
+ field: 'functionalRequirements',
168
+ message: `Requirement ${fr.id} depends on unknown requirement ${depId}`,
169
+ suggestion: `Verify that requirement ${depId} exists`,
170
+ });
171
+ }
172
+ }
173
+ }
174
+ }
175
+ const hasMust = spec.functionalRequirements.some((fr) => fr.priority === 'must');
176
+ if (spec.functionalRequirements.length > 0 && !hasMust) {
177
+ warnings.push({
178
+ field: 'functionalRequirements',
179
+ message: 'No functional requirements have "must" priority',
180
+ suggestion: 'At least one requirement should be marked as "must"',
181
+ });
182
+ }
183
+ return { valid: errors.length === 0, errors, warnings };
184
+ }
185
+ validateCompleteness(spec) {
186
+ const missingFields = [];
187
+ const emptyFields = [];
188
+ const fieldScores = {};
189
+ const scoreField = (name, value, isComplete) => {
190
+ if (value === undefined || value === null) {
191
+ fieldScores[name] = 0;
192
+ missingFields.push(name);
193
+ return;
194
+ }
195
+ if (typeof value === 'string') {
196
+ if (value.length === 0) {
197
+ fieldScores[name] = 0;
198
+ emptyFields.push(name);
199
+ }
200
+ else {
201
+ fieldScores[name] = 1;
202
+ }
203
+ return;
204
+ }
205
+ if (Array.isArray(value)) {
206
+ if (value.length === 0) {
207
+ fieldScores[name] = 0;
208
+ emptyFields.push(name);
209
+ }
210
+ else if (isComplete && !isComplete(value)) {
211
+ fieldScores[name] = 0.5;
212
+ }
213
+ else {
214
+ fieldScores[name] = 1;
215
+ }
216
+ return;
217
+ }
218
+ fieldScores[name] = 1;
219
+ };
220
+ scoreField('title', spec.title);
221
+ scoreField('businessGoal', spec.businessGoal);
222
+ scoreField('stakeholders', spec.stakeholders);
223
+ scoreField('assumptions', spec.assumptions);
224
+ scoreField('constraints', spec.constraints);
225
+ scoreField('functionalRequirements', spec.functionalRequirements, (v) => {
226
+ const reqs = v;
227
+ return reqs.every((r) => r.acceptanceCriteria.length > 0);
228
+ });
229
+ scoreField('nonFunctionalRequirements', spec.nonFunctionalRequirements);
230
+ scoreField('acceptanceCriteria', spec.acceptanceCriteria);
231
+ scoreField('risks', spec.risks);
232
+ scoreField('dependencies', spec.dependencies);
233
+ scoreField('definitionOfDone', spec.definitionOfDone);
234
+ let score = 0;
235
+ for (const [field, weight] of Object.entries(COMPLETENESS_WEIGHTS)) {
236
+ score += (fieldScores[field] ?? 0) * weight;
237
+ }
238
+ return {
239
+ score: Math.round(score * 100) / 100,
240
+ missingFields,
241
+ emptyFields,
242
+ fieldScores,
243
+ };
244
+ }
245
+ }
@@ -0,0 +1,4 @@
1
+ export { DefaultSpecificationValidator } from './default-specification-validator';
2
+ export { DefaultSpecificationMerger } from './default-specification-merger';
3
+ export { serializeSpecification, deserializeSpecification } from './specification-serializer';
4
+ export { createNextVersion } from './version-manager';
@@ -0,0 +1,4 @@
1
+ export { DefaultSpecificationValidator } from './default-specification-validator';
2
+ export { DefaultSpecificationMerger } from './default-specification-merger';
3
+ export { serializeSpecification, deserializeSpecification } from './specification-serializer';
4
+ export { createNextVersion } from './version-manager';
@@ -0,0 +1,10 @@
1
+ import type { CanonicalSpecification } from '@ai-dev-orchestrator/schemas';
2
+ export declare function serializeSpecification(spec: CanonicalSpecification): string;
3
+ /**
4
+ * Deserialize a specification from frontmatter+markdown format.
5
+ *
6
+ * Body section parsing (stakeholders, requirements, etc.) is not yet implemented.
7
+ * All body sections will be returned as empty arrays. Only frontmatter fields
8
+ * (id, version, title, businessGoal, sources, analysis, etc.) are preserved.
9
+ */
10
+ export declare function deserializeSpecification(content: string): CanonicalSpecification;
@@ -0,0 +1,176 @@
1
+ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
2
+ const FRONTMATTER_DELIMITER = '---';
3
+ export function serializeSpecification(spec) {
4
+ const frontmatter = {
5
+ id: spec.id,
6
+ version: spec.version,
7
+ title: spec.title,
8
+ businessGoal: spec.businessGoal,
9
+ createdAt: spec.createdAt,
10
+ updatedAt: spec.updatedAt,
11
+ };
12
+ if (spec.previousVersion) {
13
+ frontmatter['previousVersion'] = spec.previousVersion;
14
+ }
15
+ if (spec.sources.length > 0) {
16
+ frontmatter['sources'] = spec.sources;
17
+ }
18
+ if (spec.analysis) {
19
+ frontmatter['analysis'] = spec.analysis;
20
+ }
21
+ if (spec.extensions && Object.keys(spec.extensions).length > 0) {
22
+ frontmatter['extensions'] = spec.extensions;
23
+ }
24
+ const yaml = stringifyYaml(frontmatter);
25
+ const body = serializeBody(spec);
26
+ return `${FRONTMATTER_DELIMITER}\n${yaml}${FRONTMATTER_DELIMITER}\n\n${body}`;
27
+ }
28
+ /**
29
+ * Deserialize a specification from frontmatter+markdown format.
30
+ *
31
+ * Body section parsing (stakeholders, requirements, etc.) is not yet implemented.
32
+ * All body sections will be returned as empty arrays. Only frontmatter fields
33
+ * (id, version, title, businessGoal, sources, analysis, etc.) are preserved.
34
+ */
35
+ export function deserializeSpecification(content) {
36
+ const parts = content.split(FRONTMATTER_DELIMITER);
37
+ if (parts.length < 3) {
38
+ throw new Error('Invalid specification format: missing YAML frontmatter delimiters');
39
+ }
40
+ const yamlContent = parts[1].trim();
41
+ const frontmatter = parseYaml(yamlContent);
42
+ const body = parts.slice(2).join(FRONTMATTER_DELIMITER).trim();
43
+ const bodyData = parseBody(body);
44
+ return {
45
+ id: (frontmatter['id'] ?? ''),
46
+ version: Number(frontmatter['version'] ?? 1),
47
+ previousVersion: frontmatter['previousVersion'],
48
+ title: frontmatter['title'] ?? '',
49
+ businessGoal: frontmatter['businessGoal'] ?? '',
50
+ stakeholders: bodyData.stakeholders,
51
+ assumptions: bodyData.assumptions,
52
+ constraints: bodyData.constraints,
53
+ functionalRequirements: bodyData.functionalRequirements,
54
+ nonFunctionalRequirements: bodyData.nonFunctionalRequirements,
55
+ acceptanceCriteria: bodyData.acceptanceCriteria,
56
+ risks: bodyData.risks,
57
+ dependencies: bodyData.dependencies,
58
+ definitionOfDone: bodyData.definitionOfDone,
59
+ sources: frontmatter['sources'] ?? [],
60
+ createdAt: frontmatter['createdAt'] ?? '',
61
+ updatedAt: frontmatter['updatedAt'] ?? '',
62
+ extensions: frontmatter['extensions'],
63
+ analysis: frontmatter['analysis'],
64
+ };
65
+ }
66
+ // ---------------------------------------------------------------------------
67
+ // Body serializer / parser
68
+ // ---------------------------------------------------------------------------
69
+ function serializeBody(spec) {
70
+ const sections = [];
71
+ if (spec.stakeholders.length > 0) {
72
+ sections.push('## Stakeholders\n');
73
+ sections.push('| Name | Role | Interest |');
74
+ sections.push('| ---- | ---- | -------- |');
75
+ for (const s of spec.stakeholders) {
76
+ sections.push(`| ${s.name} | ${s.role} | ${s.interest} |`);
77
+ }
78
+ sections.push('');
79
+ }
80
+ if (spec.assumptions.length > 0) {
81
+ sections.push('## Assumptions\n');
82
+ for (const a of spec.assumptions) {
83
+ const validated = a.validated ? 'Validated.' : 'Not yet validated.';
84
+ sections.push(`- **${a.id}** (${a.impact}): ${a.description} _${validated}_`);
85
+ }
86
+ sections.push('');
87
+ }
88
+ if (spec.constraints.length > 0) {
89
+ sections.push('## Constraints\n');
90
+ for (const c of spec.constraints) {
91
+ sections.push(`- **${c.id}** (${c.type}): ${c.description} Source: ${c.source}`);
92
+ }
93
+ sections.push('');
94
+ }
95
+ if (spec.functionalRequirements.length > 0) {
96
+ sections.push('## Functional Requirements\n');
97
+ for (const fr of spec.functionalRequirements) {
98
+ sections.push(`### ${fr.id}: ${fr.title} (${fr.priority})\n`);
99
+ sections.push(fr.description);
100
+ if (fr.acceptanceCriteria.length > 0) {
101
+ sections.push('\n**Acceptance Criteria:**\n');
102
+ for (const ac of fr.acceptanceCriteria) {
103
+ sections.push(`- ${ac}`);
104
+ }
105
+ }
106
+ if (fr.dependencies && fr.dependencies.length > 0) {
107
+ sections.push(`\nDependencies: ${fr.dependencies.join(', ')}`);
108
+ }
109
+ sections.push('');
110
+ }
111
+ }
112
+ if (spec.nonFunctionalRequirements.length > 0) {
113
+ sections.push('## Non-Functional Requirements\n');
114
+ for (const nfr of spec.nonFunctionalRequirements) {
115
+ let line = `- **${nfr.id}** (${nfr.category}): ${nfr.description}`;
116
+ if (nfr.metric) {
117
+ line += ` Metric: ${nfr.metric}`;
118
+ }
119
+ if (nfr.threshold) {
120
+ line += ` Threshold: ${nfr.threshold}`;
121
+ }
122
+ sections.push(line);
123
+ }
124
+ sections.push('');
125
+ }
126
+ if (spec.acceptanceCriteria.length > 0) {
127
+ sections.push('## Acceptance Criteria\n');
128
+ for (const ac of spec.acceptanceCriteria) {
129
+ sections.push(`- **${ac.id}** (${ac.verificationMethod}): ${ac.description} Requirements: ${ac.requirementIds.join(', ')}`);
130
+ }
131
+ sections.push('');
132
+ }
133
+ if (spec.risks.length > 0) {
134
+ sections.push('## Risks\n');
135
+ for (const r of spec.risks) {
136
+ let line = `- **${r.id}** (likelihood: ${r.likelihood}, impact: ${r.impact}): ${r.description}`;
137
+ if (r.mitigation) {
138
+ line += ` Mitigation: ${r.mitigation}`;
139
+ }
140
+ sections.push(line);
141
+ }
142
+ sections.push('');
143
+ }
144
+ if (spec.dependencies.length > 0) {
145
+ sections.push('## Dependencies\n');
146
+ for (const d of spec.dependencies) {
147
+ let line = `- **${d.id}** (${d.type}, ${d.status}): ${d.description}`;
148
+ if (d.owner) {
149
+ line += ` Owner: ${d.owner}`;
150
+ }
151
+ sections.push(line);
152
+ }
153
+ sections.push('');
154
+ }
155
+ if (spec.definitionOfDone.length > 0) {
156
+ sections.push('## Definition of Done\n');
157
+ for (const item of spec.definitionOfDone) {
158
+ sections.push(`- ${item}`);
159
+ }
160
+ sections.push('');
161
+ }
162
+ return sections.join('\n');
163
+ }
164
+ function parseBody(_body) {
165
+ return {
166
+ stakeholders: [],
167
+ assumptions: [],
168
+ constraints: [],
169
+ functionalRequirements: [],
170
+ nonFunctionalRequirements: [],
171
+ acceptanceCriteria: [],
172
+ risks: [],
173
+ dependencies: [],
174
+ definitionOfDone: [],
175
+ };
176
+ }
@@ -0,0 +1,2 @@
1
+ import type { CanonicalSpecification } from '@ai-dev-orchestrator/schemas';
2
+ export declare function createNextVersion(previous: CanonicalSpecification, updates: Partial<Omit<CanonicalSpecification, 'id' | 'version' | 'previousVersion' | 'createdAt'>>): CanonicalSpecification;
@@ -0,0 +1,13 @@
1
+ import { createSpecificationId } from '../domain/types';
2
+ export function createNextVersion(previous, updates) {
3
+ const now = new Date().toISOString();
4
+ return {
5
+ ...previous,
6
+ ...updates,
7
+ id: createSpecificationId(),
8
+ version: previous.version + 1,
9
+ previousVersion: previous.id,
10
+ createdAt: previous.createdAt,
11
+ updatedAt: now,
12
+ };
13
+ }
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@ai-dev-orchestrator/specification",
3
+ "version": "0.1.1",
4
+ "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/caponetto/ai-dev-orchestrator.git",
8
+ "directory": "packages/specification"
9
+ },
10
+ "type": "module",
11
+ "engines": {
12
+ "node": ">=22"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "dependencies": {
24
+ "yaml": "^2.9.0",
25
+ "zod": "^4.5.4",
26
+ "@ai-dev-orchestrator/ports": "0.1.1",
27
+ "@ai-dev-orchestrator/schemas": "0.1.1"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^26.4.0",
31
+ "vitest": "^4.1.11",
32
+ "@ai-dev-orchestrator/build-config": "0.1.1"
33
+ },
34
+ "scripts": {
35
+ "clean": "rimraf dist tsconfig.build.tsbuildinfo",
36
+ "build:base": "rimraf dist tsconfig.build.tsbuildinfo && tsc -p tsconfig.build.json",
37
+ "build:dev": "pnpm run build:base",
38
+ "build:prod": "pnpm run clean && tsc -p tsconfig.build.json --sourceMap false --declarationMap false",
39
+ "lint": "eslint src/",
40
+ "test:unit": "vitest run",
41
+ "typecheck": "tsc -p tsconfig.build.json --noEmit"
42
+ }
43
+ }