sdd-flow 2.0.1 → 2.1.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.
@@ -0,0 +1,210 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const crypto = require('node:crypto');
6
+ const io = require('./io');
7
+ const project = require('./project');
8
+ const catalog = require('./catalog');
9
+ const history = require('./history');
10
+
11
+ function actor(by, reason) {
12
+ if (!by?.trim() || !reason?.trim()) throw new Error('Provide --by and --reason');
13
+ }
14
+
15
+ function folder(spec, name, number) {
16
+ let slug = name === undefined ? spec.name : name.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
17
+ if (!slug || slug.length > 128) throw new Error('Folder name must produce a slug of 1–128 characters');
18
+ if (number !== undefined) {
19
+ if (!/^\d+$/.test(String(number)) || !Number.isSafeInteger(Number(number)) || Number(number) < 1) throw new Error('--number must be a positive safe integer');
20
+ slug = String(Number(number)).padStart(3, '0') + '-' + slug.replace(/^\d+-/, '');
21
+ }
22
+ return slug;
23
+ }
24
+
25
+ function impacts(root, spec) {
26
+ const result = [];
27
+ const inventory = catalog.registry(root);
28
+ const prefixes = [...new Set([spec.relative, ...catalog.AREAS.flatMap(area =>
29
+ [spec.id, spec.name, ...(inventory.records[spec.id]?.aliases || [])].map(name => area + '/' + name))])];
30
+ for (const item of project.specDirectories(root)) {
31
+ if (item.id === spec.id) continue;
32
+ let other;
33
+ try { other = project.loadSpec(root, item.id); }
34
+ catch (error) {
35
+ result.push({ spec: item.id, field: 'manifest', target: item.relative, effect: 'Could not inspect this spec: ' + error.message });
36
+ continue;
37
+ }
38
+ if (other.legacy || ['closed', 'cancelled'].includes(other.change.status)) continue;
39
+ if (other.change.depends_on?.includes(spec.id)) result.push({ spec: other.id, field: 'depends_on', target: spec.id,
40
+ effect: spec.change?.status === 'closed' ? 'Retained closure summary can satisfy the historical execution dependency; current contracts and tests still matter.' : 'Execution dependency will be unresolved; review this prerequisite before implementation.' });
41
+ if (other.change.related?.includes(spec.id)) result.push({ spec: other.id, field: 'related', target: spec.id, effect: 'Historical link only; missing content is a warning.' });
42
+ for (const field of ['sources', 'context', 'capabilities', 'decisions']) for (const ref of other.change[field] || []) {
43
+ const file = typeof ref === 'string' ? ref : ref.path;
44
+ if (prefixes.some(prefix => file?.startsWith(prefix + '/'))) result.push({ spec: other.id, field, target: file,
45
+ effect: catalog.historical(ref) ? 'Historical source may become unavailable; warning only.'
46
+ : 'Required reference may become unavailable. Consolidate it outside the discarded spec or revise the reference.' });
47
+ }
48
+ }
49
+ return result;
50
+ }
51
+
52
+ function inspect(root) {
53
+ const issues = [];
54
+ const entries = project.specDirectories(root, { issues });
55
+ const ids = new Set();
56
+ const updates = [];
57
+ const missing = [];
58
+ const value = catalog.registry(root);
59
+ for (const item of entries) {
60
+ if (ids.has(item.id)) throw new Error('Duplicate spec identity: ' + item.id);
61
+ ids.add(item.id);
62
+ }
63
+ for (const item of entries) {
64
+ if (item.invalid) continue;
65
+ const spec = project.loadSpec(root, item.id);
66
+ const record = value.records[item.id];
67
+ if (!record || record.path !== item.relative || record.status !== (spec.change?.status || 'legacy') ||
68
+ io.digest(record.closure || null) !== io.digest(closure(spec))) {
69
+ updates.push({ id: item.id, path: item.relative, action: record ? 'refresh-observed-location-or-state' : 'record-observed-spec' });
70
+ }
71
+ if (spec.legacy || ['closed', 'cancelled'].includes(spec.change.status)) continue;
72
+ for (const dependency of spec.change.depends_on || []) {
73
+ let target;
74
+ try { target = catalog.dependency(root, dependency); }
75
+ catch (error) {
76
+ issues.push({ spec: spec.id, field: 'depends_on', target: dependency, kind: 'invalid-prerequisite', remedy: error.message });
77
+ continue;
78
+ }
79
+ if (target.missing) issues.push({ spec: spec.id, field: 'depends_on', target: dependency, kind: 'unresolved-prerequisite',
80
+ remedy: 'Restore the source if available, or inspect current code/contracts/tests and revise this dependency. Do not restart the spec or invent completion.' });
81
+ else if (target.retained) issues.push({ spec: spec.id, field: 'depends_on', target: dependency, kind: 'retained-closure',
82
+ remedy: 'Only a recorded historical closure remains. Use current capability contracts and the consumer acceptance checks.' });
83
+ }
84
+ for (const field of ['sources', 'context', 'capabilities', 'decisions']) for (const ref of spec.change[field] || []) {
85
+ try {
86
+ const resolved = catalog.reference(root, ref);
87
+ if (resolved.missing) issues.push({ spec: spec.id, field, target: resolved.declared, kind: 'missing-historical-reference', remedy: 'Keep the provenance note or remove this optional historical link; no implementation blocker.' });
88
+ } catch (error) {
89
+ issues.push({ spec: spec.id, field, target: typeof ref === 'string' ? ref : ref?.path, kind: 'required-reference-error',
90
+ remedy: 'Restore the source, consolidate its current contract, or revise the reference. ' + error.message });
91
+ }
92
+ }
93
+ }
94
+ for (const [id, record] of Object.entries(value.records)) {
95
+ if (!ids.has(id) && record.availability !== 'purged' && (record.path ? !io.exists(root, record.path) : record.availability === 'missing')) {
96
+ missing.push({ id, path: record.path, previous_status: record.status, retained_closure: Boolean(record.status === 'closed' && record.closure) });
97
+ }
98
+ }
99
+ for (const id of value.ids) if (!value.records[id] && !ids.has(id)) {
100
+ missing.push({ id, path: null, previous_status: null, retained_closure: false });
101
+ }
102
+ return { updates, missing, issues };
103
+ }
104
+
105
+ function closure(spec) {
106
+ return spec.change?.closure ? Object.fromEntries(['at', 'run_id', 'validation', 'acceptance_verified', 'outcome'].map(key => [key, spec.change.closure[key] ?? null])) : null;
107
+ }
108
+
109
+ function reconcile(root, { dryRun = false } = {}) {
110
+ const result = inspect(root);
111
+ if (!dryRun) {
112
+ for (const item of result.updates) catalog.remember(root, project.loadSpec(root, item.id));
113
+ if (result.missing.length) {
114
+ const value = catalog.registry(root);
115
+ for (const item of result.missing) value.records[item.id] = {
116
+ ...(value.records[item.id] || { path: null, status: 'unknown', aliases: [] }), availability: 'missing',
117
+ };
118
+ io.writeJson(root, catalog.REGISTRY, value);
119
+ }
120
+ }
121
+ return { ...result, dry_run: dryRun, next: 'Only observed inventory metadata is reconciled. Business references, authorization and evidence are not rewritten; review the reported issues locally.' };
122
+ }
123
+
124
+ function validateDestination(root, spec, target) {
125
+ io.resolve(root, target);
126
+ if (io.exists(root, target)) throw new Error('Spec destination already exists: ' + target);
127
+ const all = project.specDirectories(root, { includeTrash: true });
128
+ const name = path.posix.basename(target);
129
+ const value = catalog.registry(root);
130
+ if (value.ids.some(id => id !== spec.id && id === name) || Object.entries(value.records).some(([id, record]) => id !== spec.id && record.aliases?.includes(name))) {
131
+ throw new Error('Folder name conflicts with a reserved spec identity or alias: ' + name);
132
+ }
133
+ if (all.some(other => other.id !== spec.id && (other.name === name || other.id === name || value.records[other.id]?.aliases?.includes(name)))) {
134
+ throw new Error('Folder name conflicts with another spec identity or alias: ' + name);
135
+ }
136
+ }
137
+
138
+ function move(root, spec, target, { by, reason, type, extra = {} }) {
139
+ validateDestination(root, spec, target);
140
+ const previous = spec.relative;
141
+ const inventory = io.exists(root, catalog.REGISTRY) ? io.read(root, catalog.REGISTRY) : null;
142
+ const event = history.record(root, spec, type, { by, reason, from: previous, to: target, id_preserved: spec.id });
143
+ let moved = false;
144
+ try {
145
+ fs.mkdirSync(path.dirname(io.resolve(root, target)), { recursive: true });
146
+ fs.renameSync(io.resolve(root, previous), io.resolve(root, target));
147
+ moved = true;
148
+ spec.relative = target;
149
+ catalog.remember(root, spec, extra);
150
+ } catch (error) {
151
+ if (moved) fs.renameSync(io.resolve(root, target), io.resolve(root, previous));
152
+ spec.relative = previous;
153
+ const eventPath = previous + '/' + event.path;
154
+ if (io.exists(root, eventPath)) fs.unlinkSync(io.resolve(root, eventPath));
155
+ if (inventory !== null) io.write(root, catalog.REGISTRY, inventory);
156
+ else if (io.exists(root, catalog.REGISTRY)) fs.unlinkSync(io.resolve(root, catalog.REGISTRY));
157
+ throw error;
158
+ }
159
+ return { id: spec.id, path: target, previous_path: previous, event: event.path };
160
+ }
161
+
162
+ function manage(root, operation, selector, { name, number, by, reason, permanent = false, dryRun = false } = {}) {
163
+ actor(by, reason);
164
+ const spec = project.loadSpec(root, selector, { includeTrash: true });
165
+ if (spec.legacy) throw new Error('Migrate this legacy spec before changing its identity/location');
166
+ const location = spec.relative.startsWith(catalog.TRASH + '/') ? 'trash' : spec.relative.startsWith('agents/archive/') ? 'archive' : 'active';
167
+ const record = catalog.registry(root).records[spec.id];
168
+ let target;
169
+ if (operation === 'rename') {
170
+ if (name === undefined && number === undefined) throw new Error('Provide --name and/or --number');
171
+ if (location === 'trash') throw new Error('Restore a removed spec before renaming it');
172
+ target = path.posix.dirname(spec.relative) + '/' + folder(spec, name, number);
173
+ } else if (operation === 'archive') {
174
+ if (location !== 'active') throw new Error('Only an active spec can be archived');
175
+ target = 'agents/archive/' + spec.name;
176
+ } else if (operation === 'restore') {
177
+ if (location === 'active') throw new Error('Spec is already active');
178
+ const previous = location === 'trash' ? record?.restore_path : null;
179
+ target = previous || 'agents/specs/' + spec.name;
180
+ if (name) target = path.posix.dirname(target) + '/' + folder(spec, name);
181
+ } else if (operation === 'remove') {
182
+ if (location === 'trash' && !permanent) throw new Error('Spec is already in recoverable trash; use restore or remove --permanent');
183
+ target = location === 'trash' ? spec.relative : catalog.TRASH + '/' + spec.id + '-' + crypto.randomUUID().slice(0, 8);
184
+ } else throw new Error('Unknown spec management operation');
185
+ if (target === spec.relative && operation !== 'remove') throw new Error('Spec destination is unchanged');
186
+ io.resolve(root, target);
187
+ if (target !== spec.relative && io.exists(root, target)) throw new Error('Spec destination already exists: ' + target);
188
+ if (target !== spec.relative) validateDestination(root, spec, target);
189
+ const impact = impacts(root, spec);
190
+ const result = { operation, id: spec.id, from: spec.relative, to: permanent ? null : target, permanent, dry_run: dryRun, impacts: impact };
191
+ if (dryRun) return result;
192
+ const extra = operation === 'remove' ? { restore_path: record?.restore_path || spec.relative, removed: { by, reason, at: new Date().toISOString() } }
193
+ : { availability: 'present' };
194
+ if (target !== spec.relative) move(root, spec, target, { by, reason, type: operation, extra });
195
+ if (operation === 'remove' && permanent) {
196
+ const value = catalog.registry(root);
197
+ value.records[spec.id] = { ...value.records[spec.id], path: null, availability: 'purged', purged: { by, reason, at: new Date().toISOString() } };
198
+ io.writeJson(root, catalog.REGISTRY, value);
199
+ try { fs.rmSync(io.resolve(root, target), { recursive: true }); }
200
+ catch (error) {
201
+ value.records[spec.id].path = target;
202
+ value.records[spec.id].availability = 'purge-incomplete';
203
+ io.writeJson(root, catalog.REGISTRY, value);
204
+ throw new Error('Permanent removal was interrupted; inspect ' + target + ': ' + error.message);
205
+ }
206
+ }
207
+ return { ...result, dry_run: false, status: spec.change.status, next: 'Identity and business scope were preserved. Review affected references; current code is not rolled back or deleted.' };
208
+ }
209
+
210
+ module.exports = { manage, reconcile, inspect, impacts };
package/lib/markdown.js CHANGED
@@ -1,71 +1,71 @@
1
- 'use strict';
2
-
3
- const YAML = require('yaml');
4
- const io = require('./io');
5
-
6
- function parseYaml(source, label = 'YAML') {
7
- const document = YAML.parseDocument(source, { uniqueKeys: true, strict: true, schema: 'core' });
8
- if (document.errors.length || document.warnings.length) {
9
- throw new Error(label + ': ' + [...document.errors, ...document.warnings].map(e => e.message).join('; '));
10
- }
11
- let result;
12
- try { result = document.toJS({ maxAliasCount: 0 }); }
13
- catch (error) { throw new Error(label + ': ' + error.message); }
14
- if (!result || typeof result !== 'object' || Array.isArray(result)) throw new Error(label + ': expected a mapping');
15
- function inspect(value) {
16
- if (!value || typeof value !== 'object') return;
17
- for (const [key, child] of Object.entries(value)) {
18
- if (['__proto__', 'constructor', 'prototype'].includes(key)) throw new Error(label + ': reserved key ' + key);
19
- inspect(child);
20
- }
21
- }
22
- inspect(result);
23
- return result;
24
- }
25
-
26
- function parseMarkdown(source, label = 'Markdown', required = true) {
27
- const normalized = source.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n');
28
- if (!normalized.startsWith('---\n')) {
29
- if (required) throw new Error(label + ': missing YAML front matter; run sdd migrate for legacy specs');
30
- return { data: {}, body: normalized, legacy: true };
31
- }
32
- let end = normalized.indexOf('\n---\n', 4);
33
- if (end < 0 && normalized.endsWith('\n---')) end = normalized.length - 4;
34
- if (end < 0) throw new Error(label + ': unclosed front matter');
35
- if (end > 65536) throw new Error(label + ': front matter exceeds 64 KiB');
36
- return { data: parseYaml(normalized.slice(4, end), label), body: normalized.slice(end + 5).replace(/^\n/, ''), legacy: false };
37
- }
38
-
39
- function markdown(data, body) {
40
- return '---\n' + YAML.stringify(data, { lineWidth: 0, aliasDuplicateObjects: false }).trimEnd() + '\n---\n\n' + body.trim() + '\n';
41
- }
42
-
43
- function load(root, relative, required = true) {
44
- return parseMarkdown(io.read(root, relative), relative, required);
45
- }
46
-
47
- function section(body, heading, label) {
48
- const lines = body.split('\n');
49
- let start = -1;
50
- let level = 0;
51
- let fenced = false;
52
- let fenceCharacter;
53
- let fenceLength;
54
- for (let index = 0; index < lines.length; index++) {
55
- const fence = lines[index].match(/^\s*(`{3,}|~{3,})/);
56
- if (fence) {
57
- if (!fenced) { fenced = true; fenceCharacter = fence[1][0]; fenceLength = fence[1].length; }
58
- else if (fence[1][0] === fenceCharacter && fence[1].length >= fenceLength) fenced = false;
59
- continue;
60
- }
61
- if (fenced) continue;
62
- const match = lines[index].match(/^(#{1,6})\s+(.+?)\s*#*\s*$/);
63
- if (!match) continue;
64
- if (start >= 0 && match[1].length <= level) return lines.slice(start, index).join('\n').trim();
65
- if (match[2] === heading) { start = index; level = match[1].length; }
66
- }
67
- if (start < 0) throw new Error(label + ': heading not found: ' + heading);
68
- return lines.slice(start).join('\n').trim();
69
- }
70
-
71
- module.exports = { parseYaml, parseMarkdown, markdown, load, section };
1
+ 'use strict';
2
+
3
+ const YAML = require('yaml');
4
+ const io = require('./io');
5
+
6
+ function parseYaml(source, label = 'YAML') {
7
+ const document = YAML.parseDocument(source, { uniqueKeys: true, strict: true, schema: 'core' });
8
+ if (document.errors.length || document.warnings.length) {
9
+ throw new Error(label + ': ' + [...document.errors, ...document.warnings].map(e => e.message).join('; '));
10
+ }
11
+ let result;
12
+ try { result = document.toJS({ maxAliasCount: 0 }); }
13
+ catch (error) { throw new Error(label + ': ' + error.message); }
14
+ if (!result || typeof result !== 'object' || Array.isArray(result)) throw new Error(label + ': expected a mapping');
15
+ function inspect(value) {
16
+ if (!value || typeof value !== 'object') return;
17
+ for (const [key, child] of Object.entries(value)) {
18
+ if (['__proto__', 'constructor', 'prototype'].includes(key)) throw new Error(label + ': reserved key ' + key);
19
+ inspect(child);
20
+ }
21
+ }
22
+ inspect(result);
23
+ return result;
24
+ }
25
+
26
+ function parseMarkdown(source, label = 'Markdown', required = true) {
27
+ const normalized = source.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n');
28
+ if (!normalized.startsWith('---\n')) {
29
+ if (required) throw new Error(label + ': missing YAML front matter; run sdd migrate for legacy specs');
30
+ return { data: {}, body: normalized, legacy: true };
31
+ }
32
+ let end = normalized.indexOf('\n---\n', 4);
33
+ if (end < 0 && normalized.endsWith('\n---')) end = normalized.length - 4;
34
+ if (end < 0) throw new Error(label + ': unclosed front matter');
35
+ if (end > 65536) throw new Error(label + ': front matter exceeds 64 KiB');
36
+ return { data: parseYaml(normalized.slice(4, end), label), body: normalized.slice(end + 5).replace(/^\n/, ''), legacy: false };
37
+ }
38
+
39
+ function markdown(data, body) {
40
+ return '---\n' + YAML.stringify(data, { lineWidth: 0, aliasDuplicateObjects: false }).trimEnd() + '\n---\n\n' + body.trim() + '\n';
41
+ }
42
+
43
+ function load(root, relative, required = true) {
44
+ return parseMarkdown(io.read(root, relative), relative, required);
45
+ }
46
+
47
+ function section(body, heading, label) {
48
+ const lines = body.split('\n');
49
+ let start = -1;
50
+ let level = 0;
51
+ let fenced = false;
52
+ let fenceCharacter;
53
+ let fenceLength;
54
+ for (let index = 0; index < lines.length; index++) {
55
+ const fence = lines[index].match(/^\s*(`{3,}|~{3,})/);
56
+ if (fence) {
57
+ if (!fenced) { fenced = true; fenceCharacter = fence[1][0]; fenceLength = fence[1].length; }
58
+ else if (fence[1][0] === fenceCharacter && fence[1].length >= fenceLength) fenced = false;
59
+ continue;
60
+ }
61
+ if (fenced) continue;
62
+ const match = lines[index].match(/^(#{1,6})\s+(.+?)\s*#*\s*$/);
63
+ if (!match) continue;
64
+ if (start >= 0 && match[1].length <= level) return lines.slice(start, index).join('\n').trim();
65
+ if (match[2] === heading) { start = index; level = match[1].length; }
66
+ }
67
+ if (start < 0) throw new Error(label + ': heading not found: ' + heading);
68
+ return lines.slice(start).join('\n').trim();
69
+ }
70
+
71
+ module.exports = { parseYaml, parseMarkdown, markdown, load, section };