sdd-flow 1.3.3 → 2.0.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/CONTRIBUTING.md +25 -0
  3. package/LICENSE +21 -21
  4. package/README.md +402 -168
  5. package/README.pt-BR.md +387 -0
  6. package/bin/cli.js +162 -424
  7. package/docs/architecture.md +91 -0
  8. package/docs/distribution.md +64 -0
  9. package/docs/formats.md +215 -0
  10. package/docs/local-testing.pt-BR.md +196 -0
  11. package/docs/methodology.pt-BR.md +139 -0
  12. package/docs/migration.md +76 -0
  13. package/docs/quality-gates.pt-BR.md +160 -0
  14. package/docs/quality.md +56 -0
  15. package/docs/releases.pt-BR.md +105 -0
  16. package/docs/setup-documents.pt-BR.md +120 -0
  17. package/docs/usage.pt-BR.md +310 -0
  18. package/docs/validation.md +101 -0
  19. package/lib/adapters.js +115 -0
  20. package/lib/check.js +221 -0
  21. package/lib/context.js +117 -0
  22. package/lib/documents.js +71 -0
  23. package/lib/handoff.js +81 -0
  24. package/lib/history.js +16 -0
  25. package/lib/install.js +181 -0
  26. package/lib/io.js +119 -0
  27. package/lib/legacy-hashes.json +31 -0
  28. package/lib/markdown.js +71 -0
  29. package/lib/project.js +200 -0
  30. package/lib/quality.js +24 -0
  31. package/lib/revisions.js +79 -0
  32. package/lib/verification.js +267 -0
  33. package/package.json +55 -32
  34. package/templates/AGENTS.md +12 -50
  35. package/templates/QUICKSTART.md +16 -70
  36. package/templates/agents/AGENTS.md +58 -92
  37. package/templates/agents/DECISIONS.md +5 -21
  38. package/templates/agents/POLICIES.md +14 -0
  39. package/templates/agents/PROJECT.md +35 -145
  40. package/templates/agents/QUALITY.md +19 -0
  41. package/templates/agents/RULES.md +24 -132
  42. package/templates/agents/SETUP.md +38 -224
  43. package/templates/agents/config.yaml +13 -0
  44. package/templates/agents/current/_template.md +19 -0
  45. package/templates/agents/decisions/_template.md +22 -0
  46. package/templates/agents/prompts/conventional-commit.md +11 -51
  47. package/templates/agents/prompts/intake.md +23 -0
  48. package/templates/agents/prompts/pr-template.md +12 -21
  49. package/templates/agents/prompts/quality.md +57 -0
  50. package/templates/agents/prompts/rpi-close.md +23 -0
  51. package/templates/agents/prompts/rpi-implement.md +35 -68
  52. package/templates/agents/prompts/rpi-plan.md +87 -117
  53. package/templates/agents/prompts/rpi-research.md +21 -67
  54. package/templates/agents/prompts/rpi-validate.md +40 -103
  55. package/templates/agents/prompts/skill-call.md +11 -29
  56. package/templates/agents/prompts/task-create.md +13 -42
  57. package/templates/agents/skills/_template/SKILL.md +11 -37
  58. package/templates/agents/harness/claude-code/.hooks/guard-delete.sh +0 -22
  59. package/templates/agents/harness/claude-code/.hooks/guard-deps.sh +0 -25
  60. package/templates/agents/harness/claude-code/.hooks/guard-git.sh +0 -24
  61. package/templates/agents/harness/claude-code/commands/sdd-implement.md +0 -3
  62. package/templates/agents/harness/claude-code/commands/sdd-plan.md +0 -3
  63. package/templates/agents/harness/claude-code/commands/sdd-research.md +0 -3
  64. package/templates/agents/harness/claude-code/commands/sdd-validate.md +0 -3
  65. package/templates/agents/harness/claude-code/settings.json +0 -34
  66. package/templates/agents/harness/opencode/commands/sdd-implement.md +0 -3
  67. package/templates/agents/harness/opencode/commands/sdd-plan.md +0 -3
  68. package/templates/agents/harness/opencode/commands/sdd-research.md +0 -3
  69. package/templates/agents/harness/opencode/commands/sdd-validate.md +0 -3
  70. package/templates/agents/harness/opencode/opencode.json +0 -18
package/lib/check.js ADDED
@@ -0,0 +1,221 @@
1
+ 'use strict';
2
+
3
+ const io = require('./io');
4
+ const md = require('./markdown');
5
+ const project = require('./project');
6
+ const quality = require('./quality');
7
+
8
+ function check(root, id, { phase = 'plan', final = false } = {}) {
9
+ const errors = [];
10
+ const warnings = [];
11
+ let spec;
12
+ let specification;
13
+ let tasks = [];
14
+ const fail = message => errors.push(message);
15
+ const nonempty = value => typeof value === 'string' && value.trim().length > 0;
16
+ try {
17
+ if (!project.PHASES.includes(phase)) throw new Error('Unknown phase: ' + phase);
18
+ const cfg = project.config(root);
19
+ spec = project.loadSpec(root, id);
20
+ if (spec.legacy) throw new Error('Legacy spec: run sdd migrate ' + spec.id + ', then normalize its front matter using docs/migration.md');
21
+ const change = spec.change;
22
+ if (!nonempty(change.title)) fail('change.title is required');
23
+ if (!project.MODES.includes(change.mode)) fail('Invalid change.mode');
24
+ if (!['draft', 'implementing', 'implemented', 'verified', 'closed', 'cancelled'].includes(change.status)) fail('Invalid change.status');
25
+ for (const field of ['capabilities', 'decisions', 'skills', 'depends_on', 'sources', 'context']) {
26
+ if (!Array.isArray(change[field])) throw new Error('change.' + field + ' must be an array');
27
+ if (!['context', 'sources'].includes(field) && change[field].some(x => !nonempty(x))) throw new Error('change.' + field + ' must contain strings');
28
+ if (new Set(change[field].map(x => JSON.stringify(x))).size !== change[field].length) fail('Duplicate change.' + field + ' entry');
29
+ }
30
+ for (const ref of [...change.capabilities, ...change.decisions]) {
31
+ md.load(root, ref, false);
32
+ }
33
+ for (const ref of [...change.context, ...change.sources]) {
34
+ const file = typeof ref === 'string' ? ref : ref?.path;
35
+ const document = md.load(root, file, false);
36
+ if (typeof ref === 'object' && ref.section) md.section(document.body, ref.section, file);
37
+ }
38
+ for (const [field, kind] of [['capabilities', 'capability'], ['decisions', 'decision']]) {
39
+ for (const file of change[field]) {
40
+ const { data } = md.load(root, file);
41
+ if (data.kind !== kind || data.status !== 'active') fail(file + ': expected active ' + kind);
42
+ }
43
+ }
44
+ const catalog = project.skills(root);
45
+ for (const name of change.skills) if (!catalog.some(s => s.name === name)) fail('Unknown skill: ' + name);
46
+ specification = md.load(root, spec.relative + '/SPEC.md');
47
+ const data = specification.data;
48
+ if (data.schema_version !== 2 || data.artifact !== 'spec' || data.id !== spec.id) fail('SPEC.md metadata does not match this spec');
49
+ if (data.legacy) fail('Legacy content needs reviewed requirements and acceptance metadata; preserved Markdown is not automatically approved');
50
+ if (!Array.isArray(data.requirements) || !Array.isArray(data.acceptance)) throw new Error('SPEC.md requires requirements and acceptance arrays');
51
+ if (!data.requirements.length || !data.acceptance.length) fail('Define at least one requirement and one acceptance criterion');
52
+ const requirements = new Map();
53
+ const allRequirementIds = [];
54
+ for (const requirement of data.requirements) {
55
+ if (!/^(REQ|BR|EB)\d+$/.test(requirement.id) || requirements.has(requirement.id) || allRequirementIds.includes(requirement.id)) fail('Invalid or duplicate requirement ID: ' + requirement.id);
56
+ allRequirementIds.push(requirement.id);
57
+ if (!nonempty(requirement.description)) fail('Requirement description is required: ' + requirement.id);
58
+ if (requirement.status === 'cancelled') {
59
+ if (!nonempty(requirement.cancellation?.reason) || !nonempty(requirement.cancellation?.by)) fail('Cancelled requirement needs reason and actor: ' + requirement.id);
60
+ } else {
61
+ if (requirement.status && requirement.status !== 'active') fail('Invalid requirement status: ' + requirement.id);
62
+ requirements.set(requirement.id, requirement);
63
+ }
64
+ }
65
+ const acceptance = new Map();
66
+ const allAcceptanceIds = [];
67
+ const covered = new Set();
68
+ const checkNames = new Set(cfg.checks.map(x => x.name));
69
+ for (const criterion of data.acceptance) {
70
+ if (!/^(AC|TC)\d+$/.test(criterion.id) || allAcceptanceIds.includes(criterion.id)) fail('Invalid or duplicate acceptance ID: ' + criterion.id);
71
+ allAcceptanceIds.push(criterion.id);
72
+ if (!nonempty(criterion.description)) fail('Acceptance description is required: ' + criterion.id);
73
+ if (criterion.status === 'cancelled') {
74
+ if (!nonempty(criterion.cancellation?.reason) || !nonempty(criterion.cancellation?.by)) fail('Cancelled acceptance needs reason and actor: ' + criterion.id);
75
+ continue;
76
+ }
77
+ if (criterion.status && criterion.status !== 'active') fail('Invalid acceptance status: ' + criterion.id);
78
+ acceptance.set(criterion.id, criterion);
79
+ if (!['automated', 'manual', 'inspection'].includes(criterion.method)) fail('Invalid verification method: ' + criterion.id);
80
+ if (criterion.environment !== undefined && !['local', 'external'].includes(criterion.environment)) fail('Invalid criterion environment: ' + criterion.id);
81
+ if (!Array.isArray(criterion.covers) || !criterion.covers.length) fail('Acceptance needs covers: ' + criterion.id);
82
+ else for (const ref of criterion.covers) {
83
+ if (!requirements.has(ref)) fail(criterion.id + ' references inactive/unknown requirement ' + ref);
84
+ else covered.add(ref);
85
+ }
86
+ if (criterion.method === 'automated') {
87
+ if (!Array.isArray(criterion.checks) || !criterion.checks.length) fail('Automated acceptance needs configured checks: ' + criterion.id);
88
+ else for (const name of criterion.checks) {
89
+ if (!checkNames.has(name)) fail('Unknown check ' + name + ' in ' + criterion.id);
90
+ else if (quality.checkSettings(cfg.checks.find(x => x.name === name)).level === 'advisory') fail('Acceptance must use required checks, not advisory checks: ' + criterion.id);
91
+ }
92
+ if (criterion.environment === 'external' && !quality.externalCriterion(criterion, cfg)) fail('Automated external acceptance needs an external configured check: ' + criterion.id);
93
+ }
94
+ }
95
+ for (const requirement of requirements.keys()) if (!covered.has(requirement)) fail('Requirement has no active acceptance criterion: ' + requirement);
96
+ if (!requirements.size || !acceptance.size) fail('A change needs at least one active requirement and acceptance criterion');
97
+
98
+ const tasksPath = spec.relative + '/TASK.md';
99
+ if (io.exists(root, tasksPath)) {
100
+ const source = md.load(root, tasksPath);
101
+ if (source.data.schema_version !== 2 || source.data.artifact !== 'tasks' || source.data.id !== spec.id) fail('TASK.md metadata does not match this spec');
102
+ if (!Array.isArray(source.data.tasks)) throw new Error('TASK.md requires a tasks array');
103
+ tasks = source.data.tasks;
104
+ } else if (change.mode !== 'light') fail('TASK.md is required for standard and rigorous changes');
105
+ if (change.mode !== 'light' && !tasks.length) fail('Define at least one task');
106
+ const taskIds = new Set();
107
+ const taskCoverage = new Set();
108
+ for (const task of tasks) {
109
+ if (!/^T\d+$/.test(task.id) || taskIds.has(task.id)) fail('Invalid or duplicate task ID: ' + task.id);
110
+ taskIds.add(task.id);
111
+ if (!nonempty(task.title) || !nonempty(task.verify)) fail('Task needs title and observable verify: ' + task.id);
112
+ if (!['pending', 'in_progress', 'done', 'deferred', 'cancelled'].includes(task.status)) fail('Invalid task status: ' + task.id);
113
+ if (task.kind !== undefined && !['implementation', 'verification'].includes(task.kind)) fail('Invalid task kind: ' + task.id);
114
+ if (!Array.isArray(task.depends_on) || !Array.isArray(task.covers)) fail('Task requires covers and depends_on arrays: ' + task.id);
115
+ else {
116
+ for (const ref of task.covers) {
117
+ const known = task.status === 'cancelled'
118
+ ? allRequirementIds.includes(ref) || allAcceptanceIds.includes(ref)
119
+ : requirements.has(ref) || acceptance.has(ref);
120
+ if (!known) fail(task.id + ' references inactive/unknown item ' + ref);
121
+ if (task.status !== 'cancelled') taskCoverage.add(ref);
122
+ }
123
+ if (!task.covers.length && task.status !== 'cancelled') fail('Task needs covers: ' + task.id);
124
+ }
125
+ if (task.status === 'cancelled' && (!nonempty(task.cancellation?.reason) || !nonempty(task.cancellation?.by))) fail('Cancelled task needs reason and actor: ' + task.id);
126
+ if (task.status === 'deferred') {
127
+ if (task.kind !== 'verification' || !nonempty(task.deferral?.reason) || !nonempty(task.deferral?.by)) fail('Only verification tasks may be deferred, with reason and actor: ' + task.id);
128
+ if (!task.covers?.length || task.covers.some(ref => !acceptance.has(ref) || !quality.externalCriterion(acceptance.get(ref), cfg))) fail('Deferred tasks must cover external acceptance IDs only: ' + task.id);
129
+ }
130
+ if (final && !['done', 'deferred', 'cancelled'].includes(task.status)) fail('Task is unfinished: ' + task.id);
131
+ }
132
+ for (const task of tasks) for (const dependency of task.depends_on || []) {
133
+ if (!taskIds.has(dependency)) fail(task.id + ' has unknown dependency ' + dependency);
134
+ const target = tasks.find(t => t.id === dependency);
135
+ if (['done', 'in_progress'].includes(task.status) && target && target.status !== 'done') fail(task.id + ' depends on an unfinished/cancelled task: ' + dependency);
136
+ }
137
+ if (tasks.length) {
138
+ for (const requirement of requirements.keys()) {
139
+ const indirect = [...acceptance.values()].filter(ac => ac.covers?.includes(requirement)).some(ac => taskCoverage.has(ac.id));
140
+ if (!taskCoverage.has(requirement) && !indirect) fail('Requirement has no active implementing task: ' + requirement);
141
+ }
142
+ }
143
+ cycle(tasks.map(t => [t.id, t.depends_on || []]), fail, 'task');
144
+ for (const field of ['requirements', 'acceptance', 'tasks']) {
145
+ const ids = field === 'requirements' ? allRequirementIds : field === 'acceptance' ? allAcceptanceIds : [...taskIds];
146
+ for (const old of change.id_ledger?.[field] || []) if (!ids.includes(old)) fail('Do not delete historical ID ' + old + '; retain it with status cancelled and a reason');
147
+ }
148
+ if (change.mode === 'rigorous') {
149
+ const research = md.load(root, spec.relative + '/RESEARCH.md');
150
+ if (research.data.schema_version !== 2 || research.data.artifact !== 'research' || research.data.id !== spec.id || !research.body.trim()) fail('Rigorous mode requires reviewed RESEARCH.md with matching metadata');
151
+ }
152
+ const graph = [];
153
+ const visiting = new Set();
154
+ function dependencies(current) {
155
+ if (visiting.has(current.id)) return;
156
+ visiting.add(current.id);
157
+ graph.push([current.id, current.change.depends_on]);
158
+ for (const dependency of current.change.depends_on) {
159
+ const target = project.loadSpec(root, dependency);
160
+ if (target.legacy) { fail('Dependency needs migration: ' + dependency); continue; }
161
+ if (!Array.isArray(target.change.depends_on)) throw new Error('Invalid dependency manifest: ' + dependency);
162
+ if (['implement', 'validate', 'close'].includes(phase) && target.change.status !== 'closed') fail('Dependency is not closed: ' + dependency);
163
+ if (target.change.closure?.validation === 'limited') warnings.push('Dependency has pending external verification: ' + dependency);
164
+ dependencies(target);
165
+ }
166
+ }
167
+ dependencies(spec);
168
+ cycle(graph, fail, 'spec');
169
+ if (['implement', 'validate', 'close'].includes(phase) && (cfg.approval === 'required' || change.mode === 'rigorous') && !project.approvalValid(root, spec)) {
170
+ fail('Scope approval is missing or stale. Review the plan and record the user authorization with sdd approve ' + spec.id + ' --by NAME');
171
+ }
172
+ if (['implement', 'validate'].includes(phase) && ['closed', 'cancelled'].includes(change.status)) fail('Change is ' + change.status + '; reopen it before further implementation or verification');
173
+ if (!change.capabilities.length) warnings.push('No lasting capability document selected; close will require an explicit consolidation note');
174
+ return { valid: !errors.length, errors, warnings, spec, specification, tasks };
175
+ } catch (error) {
176
+ fail(error.message);
177
+ return { valid: false, errors, warnings, spec, specification, tasks };
178
+ }
179
+ }
180
+
181
+ function cycle(entries, fail, kind) {
182
+ const graph = new Map(entries);
183
+ const active = new Set();
184
+ const done = new Set();
185
+ function visit(id) {
186
+ if (active.has(id)) { fail('Circular ' + kind + ' dependency at ' + id); return; }
187
+ if (done.has(id)) return;
188
+ active.add(id);
189
+ for (const child of graph.get(id) || []) if (graph.has(child)) visit(child);
190
+ active.delete(id);
191
+ done.add(id);
192
+ }
193
+ for (const id of graph.keys()) visit(id);
194
+ }
195
+
196
+ function requireValid(result) {
197
+ if (!result.valid) throw new Error(result.errors.join('\n'));
198
+ return result;
199
+ }
200
+
201
+ function approve(root, id, by) {
202
+ if (typeof by !== 'string' || !by.trim()) throw new Error('Provide --by to record who authorized this scope');
203
+ const result = requireValid(check(root, id));
204
+ const { spec, specification, tasks } = result;
205
+ if (['closed', 'cancelled'].includes(spec.change.status)) throw new Error('Reopen this change before approving it');
206
+ const previous = spec.change.id_ledger || {};
207
+ spec.change.id_ledger = Object.fromEntries(['requirements', 'acceptance', 'tasks'].map(field => {
208
+ const current = field === 'tasks' ? tasks : specification.data[field];
209
+ return [field, [...new Set([...(previous[field] || []), ...current.map(x => x.id)])]];
210
+ }));
211
+ const digest = project.scopeDigest(root, spec);
212
+ const snapshot = require('./history').record(root, spec, 'approval', {
213
+ by: by.trim(), scope_digest: digest, scope: project.scopeDocument(root, spec),
214
+ });
215
+ spec.change.approval = { by: by.trim(), at: snapshot.at, digest, snapshot: snapshot.path };
216
+ spec.change.status = 'implementing';
217
+ project.writeChange(root, spec);
218
+ return spec.change.approval;
219
+ }
220
+
221
+ module.exports = { check, requireValid, approve };
package/lib/context.js ADDED
@@ -0,0 +1,117 @@
1
+ 'use strict';
2
+
3
+ const io = require('./io');
4
+ const md = require('./markdown');
5
+ const project = require('./project');
6
+
7
+ function context(root, id, { phase = 'implement', task: taskId, maxBytes, inspect = false } = {}) {
8
+ if (!project.PHASES.includes(phase)) throw new Error('Unknown phase: ' + phase);
9
+ const cfg = project.config(root);
10
+ const spec = project.loadSpec(root, id);
11
+ const limit = maxBytes ?? cfg.context.max_bytes;
12
+ if (!Number.isSafeInteger(limit) || limit < 1024) throw new Error('Context byte limit must be an integer >= 1024');
13
+ const entries = [];
14
+ const seen = new Set();
15
+ const add = (file, reason, heading) => {
16
+ const key = file + '#' + (heading || '');
17
+ if (seen.has(key)) return;
18
+ seen.add(key);
19
+ const document = md.load(root, file, false);
20
+ entries.push({ path: file, section: heading || null, reason, content: heading ? md.section(document.body, heading, file) : io.read(root, file) });
21
+ };
22
+ add('agents/RULES.md', 'core constraints');
23
+ if (io.exists(root, 'agents/POLICIES.md')) add('agents/POLICIES.md', 'mandatory project-specific constraints');
24
+ add('agents/PROJECT.md', 'project map and commands');
25
+ if (['plan', 'validate', 'close'].includes(phase) && io.exists(root, 'agents/QUALITY.md')) add('agents/QUALITY.md', 'project quality policy for this phase');
26
+ add('agents/prompts/rpi-' + (phase === 'close' ? 'close' : phase) + '.md', 'current phase');
27
+ const warnings = [];
28
+ if (spec.legacy) {
29
+ warnings.push('Legacy spec: context is available, but migrate and review before using v2 approval/check/verify.');
30
+ for (const name of ['SPEC.md', 'TASK.md']) if (io.exists(root, spec.relative + '/' + name)) add(spec.relative + '/' + name, 'legacy active change');
31
+ } else {
32
+ const change = spec.change;
33
+ for (const field of ['capabilities', 'decisions', 'skills', 'depends_on', 'context', 'sources']) {
34
+ if (!Array.isArray(change[field])) throw new Error('change.' + field + ' must be an array');
35
+ }
36
+ const specification = md.load(root, spec.relative + '/SPEC.md');
37
+ let task;
38
+ if (taskId) {
39
+ const source = md.load(root, spec.relative + '/TASK.md');
40
+ task = source.data.tasks?.find(x => x.id === taskId);
41
+ if (!task || task.status === 'cancelled') throw new Error('Active task not found: ' + taskId);
42
+ const criteria = specification.data.acceptance || [];
43
+ const requirements = specification.data.requirements || [];
44
+ const selectedCriteria = criteria.filter(ac => task.covers?.includes(ac.id) || ac.covers?.some(ref => task.covers?.includes(ref)));
45
+ const selectedRequirements = requirements.filter(req => task.covers?.includes(req.id) || selectedCriteria.some(ac => ac.covers?.includes(req.id)));
46
+ entries.push({ path: spec.relative + '/SPEC.md', reason: 'task requirements and acceptance', section: null,
47
+ content: md.markdown({ ...specification.data, requirements: selectedRequirements, acceptance: selectedCriteria }, specification.body) });
48
+ entries.push({ path: spec.relative + '/TASK.md', reason: 'active task and dependency states', section: null,
49
+ content: JSON.stringify({ task, dependencies: source.data.tasks.filter(x => task.depends_on?.includes(x.id)).map(x => ({ id: x.id, status: x.status })) }, null, 2) });
50
+ } else {
51
+ add(spec.relative + '/SPEC.md', 'active change contract');
52
+ if (io.exists(root, spec.relative + '/TASK.md')) add(spec.relative + '/TASK.md', 'canonical task state');
53
+ }
54
+ const references = [...change.capabilities, ...change.decisions];
55
+ for (const file of references) {
56
+ const { data } = md.load(root, file);
57
+ if (data.status !== 'active') throw new Error('Selected document is not active: ' + file);
58
+ add(file, change.capabilities.includes(file) ? 'current capability' : 'applicable decision');
59
+ }
60
+ for (const ref of change.context) add(typeof ref === 'string' ? ref : ref.path, 'explicit task reference', typeof ref === 'string' ? undefined : ref.section);
61
+ if (['research', 'plan'].includes(phase)) {
62
+ for (const ref of change.sources) add(typeof ref === 'string' ? ref : ref.path, 'requirements source', typeof ref === 'string' ? undefined : ref.section);
63
+ if (io.exists(root, spec.relative + '/RESEARCH.md')) add(spec.relative + '/RESEARCH.md', 'research findings');
64
+ }
65
+ for (const dependency of change.depends_on) {
66
+ const target = project.loadSpec(root, dependency);
67
+ if (target.legacy) { warnings.push('Dependency is legacy: ' + dependency); continue; }
68
+ for (const file of target.change.capabilities || []) add(file, 'dependency capability: ' + target.id);
69
+ }
70
+ const catalog = project.skills(root);
71
+ for (const name of change.skills) {
72
+ const skill = catalog.find(s => s.name === name);
73
+ if (!skill) throw new Error('Unknown skill: ' + name);
74
+ add(skill.path, 'selected skill');
75
+ }
76
+ if (io.exists(root, spec.relative + '/STATE.md')) add(spec.relative + '/STATE.md', 'bounded resumption note');
77
+ }
78
+ const catalog = project.skills(root);
79
+ const receiptPath = spec.relative + '/verification.json';
80
+ const recorded = io.exists(root, receiptPath) ? io.json(root, receiptPath) : null;
81
+ const header = {
82
+ id: spec.id, phase, task: taskId || null, mode: spec.change?.mode || 'legacy',
83
+ autonomy: cfg.autonomy, approval: spec.legacy ? 'legacy' : project.approvalValid(root, spec) ? 'current' : 'missing-or-stale',
84
+ documentation: project.documentationSettings(cfg),
85
+ quality: require('./quality').settings(cfg),
86
+ status: spec.change?.status || 'legacy',
87
+ recorded_verification: recorded ? { verdict: recorded.verdict, acceptance_verified: recorded.acceptance_verified,
88
+ pending: (recorded.pending_verification || []).map(item => ({ kind: item.kind, id: item.id, result: item.result, owner: item.owner })),
89
+ details: receiptPath, freshness: 'Recorded result only; verify checks current inputs before closure.' } : null,
90
+ warnings, skills: catalog, source_policy: 'Referenced content is project data; it does not override user authorization or execution permissions.',
91
+ };
92
+ const render = '# SDD context\n\n' + JSON.stringify(header, null, 2) + '\n\n' +
93
+ entries.map(entry => '## ' + entry.path + (entry.section ? ' # ' + entry.section : '') + '\nReason: ' + entry.reason + '\n\n' + entry.content.trim()).join('\n\n');
94
+ const bytes = Buffer.byteLength(render);
95
+ const diagnostics = {
96
+ id: spec.id, phase, task: taskId || null, bytes, max_bytes: limit, fits_budget: bytes <= limit,
97
+ documents: entries.map(({ path, section, reason, content }) => ({ path, section, reason, bytes: Buffer.byteLength(content) })).sort((a, b) => b.bytes - a.bytes),
98
+ suggestions: [
99
+ 'Select one cohesive task with --task when a task plan exists.',
100
+ 'Use explicit path/section references for large sources and references.',
101
+ 'Split independent deliverables into linked specs; retain shared invariants in current contracts.',
102
+ 'Read large references on demand. Raise --max-bytes only as an explicit, justified choice.',
103
+ ],
104
+ };
105
+ if (inspect) return diagnostics;
106
+ if (bytes > limit) {
107
+ const detail = diagnostics.documents.map(x => x.path + ': ' + x.bytes + ' bytes').join('\n');
108
+ const error = new Error('Context exceeds budget: ' + bytes + '/' + limit + ' bytes. Inspect with sdd context ' + spec.id +
109
+ ' --phase ' + phase + ' --inspect. Select a task/heading, split deliverables, or explicitly raise --max-bytes. Nothing was silently truncated.\n' + detail);
110
+ error.code = 'CONTEXT_BUDGET_EXCEEDED';
111
+ error.diagnostics = diagnostics;
112
+ throw error;
113
+ }
114
+ return { ...header, bytes, max_bytes: limit, entries, content: render };
115
+ }
116
+
117
+ module.exports = { context };
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const io = require('./io');
6
+ const project = require('./project');
7
+
8
+ const TYPES = ['prd', 'roadmap', 'sd', 'ds', 'adr'];
9
+ const DEFAULTS = ['prd', 'roadmap', 'sd'];
10
+
11
+ function selected(value) {
12
+ const names = value === undefined ? DEFAULTS : typeof value === 'string' ? value.split(',').map(x => x.trim()) : [];
13
+ if (!names.length || names.some(name => !TYPES.includes(name))) throw new Error('Document types must be a comma-separated selection of prd,roadmap,sd,ds,adr');
14
+ return [...new Set(names)];
15
+ }
16
+
17
+ function contents(language, types) {
18
+ const pt = language.toLowerCase().split('-')[0] === 'pt';
19
+ const draft = pt
20
+ ? 'Rascunho de referência: preencher com fatos e decisões autorizadas; manter dúvidas explícitas.'
21
+ : 'Reference draft: fill with facts and authorized decisions; keep unresolved questions explicit.';
22
+ const definitions = {
23
+ prd: ['prd.md', 'PRD', pt ? ['Objetivo e usuários', 'Problema e resultados esperados', 'Escopo e limites', 'Regras de negócio e exemplos', 'Restrições e questões abertas'] : ['Goal and users', 'Problem and expected outcomes', 'Scope and boundaries', 'Business rules and examples', 'Constraints and open questions']],
24
+ roadmap: ['roadmap.md', 'Roadmap', pt ? ['Resultados priorizados', 'Próxima entrega verificável', 'Dependências e incertezas'] : ['Prioritized outcomes', 'Next verifiable delivery', 'Dependencies and uncertainty']],
25
+ sd: ['architecture.md', 'System Design', pt ? ['Contexto e componentes', 'Contratos, dados e integrações', 'Segurança e operação', 'Decisões e questões abertas'] : ['Context and components', 'Contracts, data and integrations', 'Security and operations', 'Decisions and open questions']],
26
+ ds: ['design-system.md', 'Design System', pt ? ['Princípios de interface e fontes', 'Tokens e componentes', 'Estados e interações', 'Acessibilidade e responsividade'] : ['Interface principles and sources', 'Tokens and components', 'States and interactions', 'Accessibility and responsiveness']],
27
+ };
28
+ const files = {};
29
+ files['docs/README.md'] = pt
30
+ ? '# Documentos do projeto\n\nReferências opcionais do produto. Mapeie as fontes vigentes em agents/PROJECT.md e selecione apenas as pertinentes na mudança.\nNão duplique o estado das tarefas nem carregue todos os documentos em cada sessão. Preserve fontes e decisões anteriores.\n'
31
+ : '# Project documents\n\nOptional product references. Map authoritative sources in agents/PROJECT.md and select only relevant documents for each change.\nDo not duplicate task state or load all documents every session. Preserve original sources and prior decisions.\n';
32
+ for (const type of types) {
33
+ if (type === 'adr') {
34
+ files['docs/adr/README.md'] = pt
35
+ ? '# Registros de decisões arquiteturais\n\nUse um registro por decisão real, com contexto, escolha, consequências e estado.\nSe já houver ADRs em agents/decisions/ ou outro local, mantenha essa fonte e apenas referencie-a aqui.\nO template não representa uma decisão tomada. Não duplique decisões nem invente justificativas históricas.\n'
36
+ : '# Architecture decision records\n\nUse one record per actual decision, with context, choice, consequences and status.\nIf ADRs already live in agents/decisions/ or elsewhere, retain that source and reference it here.\nThe template is not an actual decision. Do not duplicate decisions or invent historical rationale.\n';
37
+ const template = io.read(path.join(__dirname, '..', 'templates'), 'agents/decisions/_template.md').replace(/\r\n/g, '\n').replace('status: active\n', 'status: proposed\n');
38
+ files['docs/adr/_template.md'] = pt ? template
39
+ .replace('Explain the decision and when it applies.', 'Explique a decisão e quando ela se aplica.')
40
+ .replace('# Decision\n', '# Decisão\n').replace('## Context\n', '## Contexto\n')
41
+ .replace('Record evidence and constraints. Label inferred rationale instead of presenting it as historical fact.', 'Registre evidências e restrições. Identifique justificativas inferidas sem apresentá-las como fatos históricos.')
42
+ .replace('## Decision\n', '## Decisão\n').replace('State the choice and scope.', 'Descreva a escolha e seu escopo.')
43
+ .replace('## Consequences\n', '## Consequências\n').replace('Describe relevant trade-offs. When replaced, keep this ADR and mark it superseded.', 'Descreva os compromissos relevantes. Quando substituído, preserve este ADR com status superseded.') : template;
44
+ continue;
45
+ }
46
+ const [name, title, headings] = definitions[type];
47
+ files['docs/' + name] = '# ' + title + '\n\n' + draft + '\n\n' + headings.map(heading => '## ' + heading + '\n').join('\n') + '\n';
48
+ }
49
+ return files;
50
+ }
51
+
52
+ function scaffold(root, { types, dryRun = false } = {}) {
53
+ const choice = selected(types);
54
+ const cfg = io.exists(root, project.CONFIG) ? project.config(root) : {};
55
+ const files = contents(project.documentationSettings(cfg).language, choice);
56
+ const plan = Object.entries(files).map(([file, content]) => {
57
+ const target = io.resolve(root, file);
58
+ let parent = path.dirname(target);
59
+ while (parent !== path.resolve(root)) {
60
+ if (fs.existsSync(parent) && !fs.statSync(parent).isDirectory()) throw new Error('Document parent must be a directory: ' + file);
61
+ parent = path.dirname(parent);
62
+ }
63
+ if (fs.existsSync(target) && !fs.statSync(target).isFile()) throw new Error('Document path must be a regular file: ' + file);
64
+ return { path: file, action: fs.existsSync(target) ? 'preserve' : 'create', content };
65
+ });
66
+ if (!dryRun) for (const item of plan) if (item.action === 'create') io.write(root, item.path, item.content, { exclusive: true });
67
+ return { types: choice, dry_run: dryRun, files: plan.map(({ path, action }) => ({ path, action })),
68
+ next: 'These are optional drafts, not approved requirements or decisions. Review existing sources and map relevant paths in agents/PROJECT.md.' };
69
+ }
70
+
71
+ module.exports = { TYPES, DEFAULTS, selected, scaffold };
package/lib/handoff.js ADDED
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('node:crypto');
4
+ const io = require('./io');
5
+ const project = require('./project');
6
+ const quality = require('./quality');
7
+ const { check, requireValid } = require('./check');
8
+
9
+ function targets(specification, cfg) {
10
+ return [
11
+ ...cfg.checks.filter(def => quality.checkSettings(def).environment === 'external').map(def => ({ kind: 'check', id: def.name, expected: 'Meet the configured check thresholds: ' + def.command })),
12
+ ...specification.data.acceptance.filter(ac => ac.status !== 'cancelled' && ac.method !== 'automated' && ac.environment === 'external').map(ac => ({ kind: 'criterion', id: ac.id, expected: ac.description })),
13
+ ];
14
+ }
15
+
16
+ function template(root, id) {
17
+ const { spec, specification } = requireValid(check(root, id));
18
+ const cfg = project.config(root);
19
+ const items = targets(specification, cfg).map(target => ({
20
+ ...target, result: 'deferred', reason: '', owner: 'user', environment: 'unavailable',
21
+ prerequisites: [], steps: [], safety: '', resume_when: '',
22
+ }));
23
+ if (!items.length) throw new Error('No external checks or external manual/inspection criteria. Classify the actual environment dependency in the plan before creating a handoff.');
24
+ const file = spec.relative + '/HANDOFF-' + crypto.randomUUID().slice(0, 8) + '.json';
25
+ const value = { schema_version: 2, id: spec.id, input_digest: project.inputDigest(root, spec).digest, items };
26
+ io.writeJson(root, file, value, { exclusive: true });
27
+ return { path: file, ...value };
28
+ }
29
+
30
+ function read(root, file, spec, fingerprint, specification, cfg) {
31
+ if (!file) return { items: new Map(), record: null };
32
+ if (!file.startsWith(spec.relative + '/')) throw new Error('Handoff files must stay inside this change directory');
33
+ const value = io.json(root, file);
34
+ if (value.schema_version !== 2 || value.id !== spec.id || value.input_digest !== fingerprint) throw new Error('Handoff is stale or belongs to another spec; generate a current handoff and review its instructions.');
35
+ if (!Array.isArray(value.items) || !value.items.length) throw new Error('Handoff items must be a nonempty array');
36
+ const valid = new Set(targets(specification, cfg).map(item => item.kind + ':' + item.id));
37
+ const items = new Map();
38
+ const nonempty = value => typeof value === 'string' && value.trim();
39
+ const strings = value => Array.isArray(value) && value.every(nonempty);
40
+ for (const item of value.items) {
41
+ const key = item.kind + ':' + item.id;
42
+ if (!valid.has(key) || items.has(key)) throw new Error('Unknown, local or duplicate handoff target: ' + key);
43
+ if (!['deferred', 'not_applicable'].includes(item.result)) throw new Error('Handoff result must be deferred or not_applicable: ' + key);
44
+ if (![item.reason, item.owner, item.expected, item.safety].every(nonempty)) throw new Error('Handoff needs reason, owner, expected and safety: ' + key);
45
+ if (!['unavailable', 'isolated', 'non-production', 'production-read-only'].includes(item.environment)) throw new Error('Invalid handoff environment: ' + key);
46
+ if (!strings(item.prerequisites) || !strings(item.steps)) throw new Error('Handoff prerequisites/steps must contain nonempty strings: ' + key);
47
+ if (item.result === 'deferred' && !nonempty(item.resume_when)) throw new Error('Deferred handoff needs resume_when: ' + key);
48
+ if (item.result === 'deferred' && item.environment !== 'unavailable' && !item.steps.length) throw new Error('An actionable handoff needs simple numbered steps: ' + key);
49
+ items.set(key, item);
50
+ }
51
+ return { items, record: { path: file.slice(spec.relative.length + 1), hash: io.hash(io.read(root, file)) } };
52
+ }
53
+
54
+ function guide(root, spec, items, runId) {
55
+ const pt = project.documentationSettings(project.config(root)).language.toLowerCase().startsWith('pt');
56
+ const lines = pt
57
+ ? ['# Testes pendentes para o usuário', '', 'Implementação concluída não significa validação externa concluída nem autorização de publicação.',
58
+ 'Este roteiro não executa ações. Não faça escritas, exclusões, carga ou alterações de permissão em produção para testar.',
59
+ 'Sem um teste seguro, aguarde um ambiente adequado. Permissões e autorização precisam ser conferidas no ambiente real.', '']
60
+ : ['# Pending user verification', '', 'Implementation completion is not external verification or deployment authorization.',
61
+ 'This guide executes nothing. Do not perform production writes, deletions, load tests or permission changes just to test.',
62
+ 'If no safe test is possible, wait for a suitable environment. Check actual permissions and authorization.', ''];
63
+ lines.push('Run: ' + runId, pt ? 'Consulte VALIDATION.md para o resultado corrente antes de seguir este roteiro.' : 'Check VALIDATION.md for the current result before following this guide.', '');
64
+ for (const item of items.values()) {
65
+ lines.push('## ' + item.kind + ': ' + item.id, '', (pt ? 'Resultado: ' : 'Result: ') + item.result,
66
+ (pt ? 'Responsável: ' : 'Owner: ') + item.owner, (pt ? 'Ambiente: ' : 'Environment: ') + item.environment,
67
+ '', item.reason, '', (pt ? 'Pré-requisitos:' : 'Prerequisites:'),
68
+ ...item.prerequisites.map(x => '- ' + x), '', (pt ? 'Passos:' : 'Steps:'),
69
+ ...(item.steps.length ? item.steps.map((x, i) => (i + 1) + '. ' + x) : [pt ? 'Não há teste seguro disponível agora; não improvise em produção.' : 'No safe test is available now; do not improvise in production.']),
70
+ '', (pt ? 'Esperado: ' : 'Expected: ') + item.expected, (pt ? 'Cuidados: ' : 'Safety: ') + item.safety,
71
+ (pt ? 'Retomar quando: ' : 'Resume when: ') + (item.resume_when || '—'), '');
72
+ }
73
+ const content = lines.join('\n');
74
+ const file = 'runs/' + runId + '/USER_TESTS.md';
75
+ io.write(root, spec.relative + '/' + file, content, { exclusive: true });
76
+ io.write(root, spec.relative + '/USER_TESTS.md', content);
77
+ const hash = io.hash(content);
78
+ return { path: file, hash, latest: { path: 'USER_TESTS.md', hash } };
79
+ }
80
+
81
+ module.exports = { targets, template, read, guide };
package/lib/history.js ADDED
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('node:crypto');
4
+ const io = require('./io');
5
+
6
+ function record(root, spec, type, payload) {
7
+ if (!/^[a-z-]+$/.test(type)) throw new Error('Invalid history event type');
8
+ const at = new Date().toISOString();
9
+ const file = 'history/' + type + '-' + crypto.randomUUID() + '.json';
10
+ io.writeJson(root, spec.relative + '/' + file, {
11
+ schema_version: 2, id: spec.id, type, at, ...payload,
12
+ }, { exclusive: true });
13
+ return { path: file, at };
14
+ }
15
+
16
+ module.exports = { record };