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
@@ -0,0 +1,79 @@
1
+ 'use strict';
2
+
3
+ const io = require('./io');
4
+ const md = require('./markdown');
5
+ const project = require('./project');
6
+ const { check, requireValid } = require('./check');
7
+ const history = require('./history');
8
+
9
+ function revise(root, id, { by, reason, dryRun = false } = {}) {
10
+ if (!by?.trim() || !reason?.trim()) throw new Error('Provide --by and --reason for the scope revision');
11
+ const { spec, tasks } = requireValid(check(root, id));
12
+ if (['closed', 'cancelled'].includes(spec.change.status)) throw new Error('Reopen the change before revising its approved scope');
13
+ const previous = spec.change.approval;
14
+ if (!previous) throw new Error('No prior approval to revise; complete the plan and record actual authorization first');
15
+ const digest = project.scopeDigest(root, spec);
16
+ if (previous.digest === digest) throw new Error('The normative scope is unchanged; continue implementation or verification');
17
+ const current = project.scopeDocument(root, spec);
18
+ let old;
19
+ if (previous.snapshot) {
20
+ const snapshot = io.json(root, spec.relative + '/' + previous.snapshot);
21
+ if (snapshot.id !== spec.id || snapshot.type !== 'approval' || io.digest(snapshot.scope) !== previous.digest) throw new Error('Prior approval snapshot does not match its recorded digest');
22
+ old = snapshot.scope;
23
+ }
24
+ const changed = new Set();
25
+ const compareItems = (before, after) => {
26
+ const a = new Map((before || []).map(item => [item.id, item]));
27
+ const b = new Map((after || []).map(item => [item.id, item]));
28
+ for (const key of new Set([...a.keys(), ...b.keys()])) if (io.digest(a.get(key) ?? null) !== io.digest(b.get(key) ?? null)) changed.add(key);
29
+ };
30
+ compareItems(old?.specification?.data?.requirements, current.specification.data.requirements);
31
+ compareItems(old?.specification?.data?.acceptance, current.specification.data.acceptance);
32
+ const criteria = [...(old?.specification?.data?.acceptance || []), ...current.specification.data.acceptance];
33
+ let linked;
34
+ do {
35
+ linked = changed.size;
36
+ for (const criterion of criteria) {
37
+ if (changed.has(criterion.id) || criterion.covers?.some(id => changed.has(id))) {
38
+ changed.add(criterion.id);
39
+ for (const id of criterion.covers || []) changed.add(id);
40
+ }
41
+ }
42
+ } while (linked !== changed.size);
43
+ const oldTasks = old?.tasks?.data?.tasks || [];
44
+ const newTasks = current.tasks?.data?.tasks || [];
45
+ const changedTasks = new Set(newTasks.filter(item => io.digest(item) !== io.digest(oldTasks.find(t => t.id === item.id) ?? null)).map(item => item.id));
46
+ const reopenAll = !old || io.digest(old.change) !== io.digest(current.change) ||
47
+ io.digest(old.policy) !== io.digest(current.policy) || old.specification.body !== current.specification.body ||
48
+ old.tasks?.body !== current.tasks?.body;
49
+ const reopened = new Set();
50
+ for (const task of tasks) {
51
+ if (['done', 'in_progress', 'deferred'].includes(task.status) && (reopenAll || changedTasks.has(task.id) || task.covers.some(item => changed.has(item)))) reopened.add(task.id);
52
+ }
53
+ let expanded;
54
+ do {
55
+ expanded = false;
56
+ for (const task of tasks) {
57
+ if (['done', 'in_progress', 'deferred'].includes(task.status) && !reopened.has(task.id) && task.depends_on.some(id => reopened.has(id))) {
58
+ reopened.add(task.id);
59
+ expanded = true;
60
+ }
61
+ }
62
+ } while (expanded);
63
+ const result = { id: spec.id, dry_run: dryRun, changed_items: [...changed], reopened_tasks: [...reopened],
64
+ conservative: reopenAll, previous_digest: previous.digest, new_digest: digest };
65
+ if (dryRun) return result;
66
+ if (io.exists(root, spec.relative + '/TASK.md')) {
67
+ const document = md.load(root, spec.relative + '/TASK.md');
68
+ for (const task of document.data.tasks) if (reopened.has(task.id)) task.status = 'pending';
69
+ io.write(root, spec.relative + '/TASK.md', md.markdown(document.data, document.body));
70
+ }
71
+ const event = history.record(root, spec, 'revision', { by: by.trim(), reason: reason.trim(), ...result, previous_approval: previous });
72
+ spec.change.approval = null;
73
+ spec.change.status = 'draft';
74
+ spec.change.last_revision = { by: by.trim(), reason: reason.trim(), at: event.at, event: event.path };
75
+ project.writeChange(root, spec);
76
+ return { ...result, event: event.path, next: 'Review impacted code/tests and record authorization for the revised scope with sdd approve.' };
77
+ }
78
+
79
+ module.exports = { revise };
@@ -0,0 +1,267 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const crypto = require('node:crypto');
5
+ const { spawn, spawnSync } = require('node:child_process');
6
+ const io = require('./io');
7
+ const md = require('./markdown');
8
+ const project = require('./project');
9
+ const { check, requireValid } = require('./check');
10
+ const quality = require('./quality');
11
+ const handoff = require('./handoff');
12
+
13
+ function evidenceTemplate(root, id, out) {
14
+ const { spec, specification } = requireValid(check(root, id));
15
+ const fingerprint = project.inputDigest(root, spec).digest;
16
+ let file = out || spec.relative + '/EVIDENCE.json';
17
+ if (!out && io.exists(root, file)) file = spec.relative + '/EVIDENCE-' + fingerprint.slice(0, 12) + '-' + crypto.randomUUID().slice(0, 8) + '.json';
18
+ const value = {
19
+ schema_version: 2, id: spec.id, input_digest: fingerprint,
20
+ cases: specification.data.acceptance.filter(ac => ac.status !== 'cancelled' && ac.method !== 'automated').map(ac => ({
21
+ id: ac.id, result: 'not_run', by: '', at: '', notes: '', artifacts: [],
22
+ })),
23
+ };
24
+ io.writeJson(root, file, value, { exclusive: true });
25
+ return { path: file, ...value };
26
+ }
27
+
28
+ function runCheck(root, checkDefinition) {
29
+ return new Promise(resolve => {
30
+ const started = new Date().toISOString();
31
+ let output = '';
32
+ let truncated = false;
33
+ let timedOut = false;
34
+ let settled = false;
35
+ const env = { ...process.env };
36
+ // A verification launched from node:test must run its own tests rather than inherit recursive-run suppression.
37
+ delete env.NODE_TEST_CONTEXT;
38
+ const child = spawn(checkDefinition.command, {
39
+ cwd: root, env, shell: true, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'],
40
+ });
41
+ function capture(chunk) {
42
+ const remaining = 1024 * 1024 - Buffer.byteLength(output);
43
+ if (chunk.length > remaining) truncated = true;
44
+ if (remaining > 0) output += chunk.subarray(0, remaining).toString();
45
+ }
46
+ child.stdout.on('data', capture);
47
+ child.stderr.on('data', capture);
48
+ const timeout = setTimeout(() => {
49
+ timedOut = true;
50
+ try {
51
+ if (process.platform === 'win32') {
52
+ const termination = spawnSync('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
53
+ if (termination.status !== 0) child.kill('SIGKILL');
54
+ }
55
+ else process.kill(-child.pid, 'SIGKILL');
56
+ } catch (error) {
57
+ if (error.code !== 'ESRCH') capture(Buffer.from(error.message));
58
+ }
59
+ }, checkDefinition.timeout_ms);
60
+ function finish(code, signal, error) {
61
+ if (settled) return;
62
+ settled = true;
63
+ clearTimeout(timeout);
64
+ if (error) capture(Buffer.from(error.message));
65
+ resolve({
66
+ name: checkDefinition.name, command: checkDefinition.command, started, finished: new Date().toISOString(),
67
+ exit_code: code, signal: signal || null, timed_out: timedOut, truncated,
68
+ result: code === 0 && !timedOut && !error ? 'passed' : 'failed', output,
69
+ });
70
+ }
71
+ child.on('error', error => finish(null, null, error));
72
+ child.on('close', (code, signal) => finish(code, signal));
73
+ });
74
+ }
75
+
76
+ function readEvidence(root, file, spec, fingerprint) {
77
+ if (!file) return { cases: [], artifacts: {} };
78
+ const evidence = io.json(root, file);
79
+ if (evidence.schema_version !== 2 || evidence.id !== spec.id || evidence.input_digest !== fingerprint) {
80
+ throw new Error('Manual/inspection evidence is stale or belongs to another spec. Run sdd evidence ' + spec.id + ', repeat the affected observations, and pass the returned path to --evidence.');
81
+ }
82
+ if (!Array.isArray(evidence.cases)) throw new Error('Evidence cases must be an array');
83
+ const seen = new Set();
84
+ const artifacts = {};
85
+ const acceptance = md.load(root, spec.relative + '/SPEC.md').data.acceptance;
86
+ for (const item of evidence.cases) {
87
+ if (seen.has(item.id)) throw new Error('Duplicate evidence case: ' + item.id);
88
+ seen.add(item.id);
89
+ const criterion = acceptance.find(ac => ac.id === item.id && ac.status !== 'cancelled');
90
+ if (!criterion || criterion.method === 'automated') throw new Error('Evidence must reference active manual/inspection criteria: ' + item.id);
91
+ if (!['passed', 'failed', 'not_run', 'blocked'].includes(item.result)) throw new Error('Invalid evidence result: ' + item.id);
92
+ if (!Array.isArray(item.artifacts)) throw new Error('Evidence artifacts must be an array: ' + item.id);
93
+ if (['passed', 'failed'].includes(item.result)) {
94
+ if (typeof item.by !== 'string' || !item.by.trim() || typeof item.notes !== 'string' || !item.notes.trim() || !Number.isFinite(Date.parse(item.at))) {
95
+ throw new Error('Executed evidence needs by, at and notes: ' + item.id);
96
+ }
97
+ }
98
+ for (const artifact of item.artifacts) {
99
+ artifacts[artifact] = io.hash(fs.readFileSync(io.resolve(root, artifact)));
100
+ }
101
+ }
102
+ return { cases: evidence.cases, artifacts };
103
+ }
104
+
105
+ async function verify(root, id, { scope = 'full', evidence: evidenceFile, handoff: handoffFile, runExternal = false } = {}) {
106
+ if (!['full', 'partial'].includes(scope)) throw new Error('Verification scope must be full or partial');
107
+ const { spec, specification, tasks } = requireValid(check(root, id, { phase: 'validate', final: scope === 'full' }));
108
+ const fingerprint = project.inputDigest(root, spec).digest;
109
+ const evidence = readEvidence(root, evidenceFile, spec, fingerprint);
110
+ const cfg = project.config(root);
111
+ const transfer = handoff.read(root, handoffFile, spec, fingerprint, specification, cfg);
112
+ const previousFile = spec.relative + '/verification.json';
113
+ const previous = io.exists(root, previousFile) ? io.json(root, previousFile) : null;
114
+ const prior = previous?.input_digest === fingerprint ? previous : null;
115
+ const runId = new Date().toISOString().replace(/[:.]/g, '-') + '-' + crypto.randomUUID().slice(0, 8);
116
+ const runs = [];
117
+ for (const definition of cfg.checks) {
118
+ const policy = quality.checkSettings(definition);
119
+ const deferred = transfer.items.get('check:' + definition.name);
120
+ const execute = policy.environment !== 'external' || runExternal;
121
+ const run = execute ? { ...await runCheck(root, definition), executed: true } : {
122
+ name: definition.name, command: definition.command, started: null, finished: new Date().toISOString(),
123
+ exit_code: null, signal: null, timed_out: false, truncated: false, executed: false,
124
+ result: deferred?.result || 'not_run', output: deferred?.reason || 'External command was not requested; no execution took place.',
125
+ };
126
+ const knownFailure = prior?.checks.find(item => item.name === definition.name && item.result === 'failed');
127
+ if (!execute && knownFailure) {
128
+ run.result = 'failed';
129
+ run.previous_failure_run = knownFailure.previous_failure_run || prior.run_id;
130
+ run.output = 'Not executed in this run. A known failure for these same inputs remains unresolved: ' + run.previous_failure_run;
131
+ }
132
+ const log = 'runs/' + runId + '/' + definition.name + '.log';
133
+ io.write(root, spec.relative + '/' + log, run.output + (run.truncated ? '\n[Output truncated at 1 MiB]\n' : ''));
134
+ const { output, ...record } = run;
135
+ runs.push({ ...record, ...policy, ...(deferred && !execute && !knownFailure && { deferral: summary(deferred) }), log, log_hash: io.hash(io.read(root, spec.relative + '/' + log)) });
136
+ }
137
+ const criteria = specification.data.acceptance.filter(ac => ac.status !== 'cancelled').map(ac => {
138
+ if (ac.method === 'automated') {
139
+ const checks = runs.filter(run => ac.checks.includes(run.name));
140
+ const result = checks.some(run => run.result === 'failed') ? 'failed'
141
+ : !checks.length || checks.some(run => run.result === 'not_run') ? 'not_run'
142
+ : checks.some(run => ['deferred', 'not_applicable'].includes(run.result)) ? 'deferred' : 'passed';
143
+ return { id: ac.id, method: ac.method, result, checks: ac.checks };
144
+ }
145
+ const entry = evidence.cases.find(item => item.id === ac.id);
146
+ const deferred = transfer.items.get('criterion:' + ac.id);
147
+ const observed = entry && ['passed', 'failed'].includes(entry.result);
148
+ const knownFailure = !observed && prior?.criteria.find(item => item.id === ac.id && item.result === 'failed');
149
+ if (knownFailure) return { id: ac.id, method: ac.method, result: 'failed', evidence: knownFailure.evidence || null,
150
+ previous_failure_run: knownFailure.previous_failure_run || prior.run_id };
151
+ return { id: ac.id, method: ac.method, result: observed ? entry.result : deferred?.result || entry?.result || 'not_run',
152
+ evidence: entry || null, ...(!observed && deferred && { deferral: summary(deferred) }) };
153
+ });
154
+ const unchanged = fingerprint === project.inputDigest(root, project.loadSpec(root, spec.id)).digest;
155
+ const required = runs.filter(run => run.level === 'required');
156
+ const deferredTasks = tasks.filter(task => task.status === 'deferred');
157
+ const unresolvedTasks = deferredTasks.some(task => task.covers.some(id => !criteria.some(ac => ac.id === id && ['deferred', 'not_applicable'].includes(ac.result))));
158
+ const unresolved = [...required, ...criteria].some(item => ['not_run', 'blocked'].includes(item.result)) || unresolvedTasks;
159
+ const limited = [...required, ...criteria].some(item => ['deferred', 'not_applicable'].includes(item.result)) || deferredTasks.length;
160
+ const pending = [
161
+ ...runs.filter(run => run.deferral).map(run => ({ kind: 'check', id: run.name, ...run.deferral })),
162
+ ...criteria.filter(ac => ac.deferral).map(ac => ({ kind: 'criterion', id: ac.id, ...ac.deferral })),
163
+ ];
164
+ const used = new Map([...transfer.items].filter(([key]) => pending.some(item => key === item.kind + ':' + item.id)));
165
+ const guide = used.size ? handoff.guide(root, spec, used, runId) : null;
166
+ const warnings = runs.filter(run => run.level === 'advisory' && run.result !== 'passed').map(run => 'Advisory check ' + run.name + ': ' + run.result);
167
+ let verdict = 'passed';
168
+ if (!unchanged || required.some(run => run.result === 'failed') || criteria.some(item => item.result === 'failed')) verdict = 'failed';
169
+ else if (scope === 'partial' || unresolved) verdict = 'partial';
170
+ else if (limited) verdict = 'limited';
171
+ if (!used.size && verdict === 'passed' && scope === 'full' && io.exists(root, spec.relative + '/USER_TESTS.md')) {
172
+ const pt = project.documentationSettings(cfg).language.toLowerCase().split('-')[0] === 'pt';
173
+ io.write(root, spec.relative + '/USER_TESTS.md', (pt
174
+ ? '# Verificação do usuário\n\nSem testes delegados pendentes nesta verificação. Consulte VALIDATION.md.\n'
175
+ : '# User verification\n\nNo delegated tests are pending in this verification. See VALIDATION.md.\n') + '\nRun: ' + runId + '\n');
176
+ }
177
+ const receipt = {
178
+ schema_version: 2, id: spec.id, run_id: runId, scope, verdict, at: new Date().toISOString(),
179
+ input_digest: fingerprint, scope_digest: project.scopeDigest(root, spec), unchanged,
180
+ task_states: tasks.map(t => ({ id: t.id, status: t.status })), checks: runs, criteria, artifacts: evidence.artifacts,
181
+ acceptance_verified: unchanged && criteria.every(item => item.result === 'passed'),
182
+ warnings, pending_verification: pending,
183
+ handoff: transfer.record ? { ...transfer.record, ...(guide && { guide }) } : null,
184
+ deferred_tasks: deferredTasks.map(task => ({ id: task.id, covers: task.covers, ...task.deferral })),
185
+ limitations: ['Check-to-criterion links are declared by the project. Passing commands do not prove semantic test coverage.',
186
+ 'Commands execute with the current user permissions; configure an isolated test environment.'],
187
+ };
188
+ io.writeJson(root, spec.relative + '/runs/' + runId + '/receipt.json', receipt, { exclusive: true });
189
+ io.writeJson(root, spec.relative + '/verification.json', receipt);
190
+ const lines = [
191
+ '# Verification — ' + spec.id, '', 'Verdict: ' + verdict, 'Scope: ' + scope,
192
+ 'Input digest: ' + fingerprint, 'Inputs unchanged during checks: ' + unchanged, '',
193
+ 'Acceptance fully verified: ' + receipt.acceptance_verified, '',
194
+ '| Criterion | Method | Result |', '|---|---|---|',
195
+ ...criteria.map(ac => '| ' + ac.id + ' | ' + ac.method + ' | ' + ac.result + ' |'), '',
196
+ '## Checks', '', ...runs.map(run => '- ' + run.name + ': ' + run.result + ', ' + run.level + ', executed: ' + run.executed + ', exit ' + run.exit_code + ', log: ' + run.log),
197
+ '', '## Limitations and user verification', '',
198
+ ...(pending.length ? pending.map(item => '- ' + item.kind + ' ' + item.id + ': ' + item.result + '; ' + item.reason + '; owner: ' + item.owner) : ['No recorded external deferrals.']),
199
+ ...(guide ? ['', 'Safe user-test instructions: USER_TESTS.md; preserved run copy: ' + guide.path] : []),
200
+ ...warnings.map(item => '- ' + item),
201
+ ...(unresolvedTasks ? ['Deferred tasks need matching current handoff results, or must be updated after actual verification.'] : []),
202
+ '', '## Review', '', 'Review assertions, scope and failure cases. This report records execution; it is not a substitute for reviewing whether the tests exercise the intended behavior.',
203
+ ];
204
+ io.write(root, spec.relative + '/VALIDATION.md', md.markdown({ schema_version: 2, artifact: 'validation', id: spec.id, verdict, scope }, lines.join('\n')));
205
+ spec.change.status = verdict === 'passed' && scope === 'full' ? 'verified' : verdict === 'limited' ? 'implemented' : 'implementing';
206
+ project.writeChange(root, spec);
207
+ return receipt;
208
+ }
209
+
210
+ function summary(item) {
211
+ return Object.fromEntries(['result', 'reason', 'owner', 'environment', 'resume_when'].map(key => [key, item[key] ?? null]));
212
+ }
213
+
214
+ function currentReceipt(root, spec) {
215
+ const file = spec.relative + '/verification.json';
216
+ if (!io.exists(root, file)) throw new Error('No verification receipt; run sdd verify ' + spec.id);
217
+ const receipt = io.json(root, file);
218
+ if (receipt.schema_version !== 2 || receipt.id !== spec.id || receipt.scope !== 'full' || !['passed', 'limited'].includes(receipt.verdict) || !receipt.unchanged) {
219
+ throw new Error('Closing requires a full passed verification or an explicit limited verification with a current handoff');
220
+ }
221
+ if (receipt.verdict === 'limited' && (!receipt.handoff || !receipt.pending_verification?.length)) throw new Error('Limited verification requires a recorded handoff');
222
+ if (receipt.input_digest !== project.inputDigest(root, spec).digest || receipt.scope_digest !== project.scopeDigest(root, spec)) {
223
+ throw new Error('Verification is stale; verify the current code and contract again');
224
+ }
225
+ for (const [file, expected] of Object.entries(receipt.artifacts || {})) {
226
+ if (io.hash(fs.readFileSync(io.resolve(root, file))) !== expected) throw new Error('Evidence artifact changed: ' + file);
227
+ }
228
+ for (const run of receipt.checks || []) {
229
+ if (io.hash(io.read(root, spec.relative + '/' + run.log)) !== run.log_hash) throw new Error('Verification log changed: ' + run.log);
230
+ }
231
+ for (const artifact of [receipt.handoff, receipt.handoff?.guide, receipt.handoff?.guide?.latest].filter(Boolean)) {
232
+ if (io.hash(io.read(root, spec.relative + '/' + artifact.path)) !== artifact.hash) throw new Error('Handoff or user-test guide changed; verify again');
233
+ }
234
+ return receipt;
235
+ }
236
+
237
+ function close(root, id, { note, by, archive = false } = {}) {
238
+ if (typeof by !== 'string' || !by.trim()) throw new Error('Provide --by to record the final review');
239
+ const { spec } = requireValid(check(root, id, { phase: 'close', final: true }));
240
+ if (spec.change.status === 'cancelled') throw new Error('A cancelled change cannot be closed');
241
+ const receipt = currentReceipt(root, spec);
242
+ if (!spec.change.capabilities.length && (typeof note !== 'string' || !note.trim())) {
243
+ throw new Error('Provide --note explaining why this change needs no lasting capability update');
244
+ }
245
+ for (const file of spec.change.capabilities) {
246
+ const doc = md.load(root, file);
247
+ if (!Array.isArray(doc.data.changes) || !doc.data.changes.includes(spec.id)) throw new Error(file + ': consolidate the verified behavior and add this spec ID to changes before verifying');
248
+ }
249
+ const target = 'agents/archive/' + spec.id;
250
+ if (archive && spec.relative !== target && io.exists(root, target)) throw new Error('Archive destination already exists: ' + target);
251
+ spec.change.status = 'closed';
252
+ spec.change.closure = { by: by.trim(), at: new Date().toISOString(), run_id: receipt.run_id,
253
+ validation: receipt.verdict, acceptance_verified: receipt.acceptance_verified ?? true,
254
+ pending_verification: receipt.pending_verification || [],
255
+ outcome: receipt.verdict === 'limited' ? 'implemented_with_limitations' : 'verified',
256
+ note: note || 'Consolidated in the selected capability documents.' };
257
+ require('./history').record(root, spec, 'closure', spec.change.closure);
258
+ project.writeChange(root, spec);
259
+ if (archive && spec.relative !== target) {
260
+ fs.mkdirSync(io.resolve(root, 'agents/archive'), { recursive: true });
261
+ fs.renameSync(io.resolve(root, spec.relative), io.resolve(root, target));
262
+ spec.relative = target;
263
+ }
264
+ return { id: spec.id, status: 'closed', path: spec.relative, closure: spec.change.closure };
265
+ }
266
+
267
+ module.exports = { evidenceTemplate, runCheck, readEvidence, verify, currentReceipt, close };
package/package.json CHANGED
@@ -1,32 +1,55 @@
1
- {
2
- "name": "sdd-flow",
3
- "version": "1.3.3",
4
- "description": "Spec Driven Development workflow for AI-assisted development (SDD + RPIV)",
5
- "bin": {
6
- "sdd-cli": "bin/cli.js",
7
- "sdd": "bin/cli.js"
8
- },
9
- "files": [
10
- "bin/",
11
- "templates/"
12
- ],
13
- "engines": {
14
- "node": ">=18"
15
- },
16
- "keywords": [
17
- "sdd",
18
- "spec-driven-development",
19
- "rpiv",
20
- "ai-workflow",
21
- "claude-code",
22
- "opencode",
23
- "agentic",
24
- "workflow"
25
- ],
26
- "author": "moisesuailab",
27
- "license": "MIT",
28
- "repository": {
29
- "type": "git",
30
- "url": "https://github.com/moisesuailab/sdd-flow.git"
31
- }
32
- }
1
+ {
2
+ "name": "sdd-flow",
3
+ "version": "2.0.1",
4
+ "description": "Portable spec-driven workflow with bounded context and evidence-based verification",
5
+ "bin": {
6
+ "sdd-cli": "bin/cli.js",
7
+ "sdd": "bin/cli.js"
8
+ },
9
+ "files": [
10
+ "bin/",
11
+ "lib/",
12
+ "templates/",
13
+ "docs/",
14
+ "CHANGELOG.md",
15
+ "README.pt-BR.md",
16
+ "CONTRIBUTING.md"
17
+ ],
18
+ "engines": {
19
+ "node": ">=22"
20
+ },
21
+ "keywords": [
22
+ "sdd",
23
+ "spec-driven-development",
24
+ "rpiv",
25
+ "ai-workflow",
26
+ "claude-code",
27
+ "opencode",
28
+ "agentic",
29
+ "workflow"
30
+ ],
31
+ "author": "moisesuailab",
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/moisesuailab/sdd-flow.git"
36
+ },
37
+ "scripts": {
38
+ "test": "node --test",
39
+ "check": "node scripts/check-package.js",
40
+ "test:coverage": "node --test --experimental-test-coverage",
41
+ "release:check": "node scripts/release-check.js",
42
+ "prepublishOnly": "npm test && npm run check"
43
+ },
44
+ "dependencies": {
45
+ "yaml": "^2.9.1"
46
+ },
47
+ "homepage": "https://github.com/moisesuailab/sdd-flow#readme",
48
+ "bugs": {
49
+ "url": "https://github.com/moisesuailab/sdd-flow/issues"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "registry": "https://registry.npmjs.org"
54
+ }
55
+ }
@@ -1,50 +1,12 @@
1
- # Agent Instructions
2
-
3
- This project uses **Spec Driven Development (SDD)** with the **Research → Plan → Implement → Validate (RPIV)**
4
- methodology. Every feature goes through four isolated phases, each in its own agent session.
5
-
6
- ---
7
-
8
- ## On session start — always read these files
9
-
10
- | File | Purpose |
11
- |---|---|
12
- | `agents/AGENTS.md` | Role definition, SDD cycle, and session rules |
13
- | `agents/PROJECT.md` | Stack, architecture, and project-specific rules |
14
- | `agents/RULES.md` | Mandatory process rules (git, tasks, decisions) |
15
-
16
- > **How to load:** Use your file reading tool to read each file above before taking any action.
17
- > Do not proceed without reading them — they define the rules for this session.
18
-
19
- ---
20
-
21
- ## Skills — load on demand
22
-
23
- Skills are in `agents/skills/<name>/SKILL.md`. Before implementing any task, scan the skills
24
- directory and read the `## When to use this skill` section of each file. Load only the skills
25
- relevant to the current task.
26
-
27
- ---
28
-
29
- ## Active spec
30
-
31
- The active spec folder is `agents/specs/<NNN-feature-name>/`. It contains:
32
- `RESEARCH.md`, `SPEC.md`, `TASK.md`, `PROGRESS.md`, `DECISIONS.md`, and `TEST.md`.
33
-
34
- When a spec folder is provided, read `SPEC.md` and `TASK.md` before implementing.
35
-
36
- ---
37
-
38
- ## RPIV prompts
39
-
40
- Full prompts for each phase are in `agents/prompts/`. Use them by reading the relevant file:
41
- - Phase 1 — Research: `agents/prompts/rpi-research.md`
42
- - Phase 2 — Plan: `agents/prompts/rpi-plan.md`
43
- - Phase 3 — Implement: `agents/prompts/rpi-implement.md`
44
- - Phase 4 — Validate: `agents/prompts/rpi-validate.md`
45
-
46
- ---
47
-
48
- ## First-time setup
49
-
50
- If `agents/PROJECT.md` does not exist yet, read `agents/SETUP.md` and follow its instructions.
1
+ <!-- sdd-flow:start -->
2
+ ## SDD Flow
3
+
4
+ Read agents/RULES.md and the short map in agents/PROJECT.md.
5
+ Read agents/POLICIES.md for mandatory project-specific constraints.
6
+ Use sdd context SPEC_ID --phase PHASE --task TASK_ID for the current change; omit --task when no task is selected.
7
+ The catalog from sdd skills list contains discovery metadata; load only relevant skill bodies.
8
+ Follow the project's approval and autonomy settings. User authorization and tool permissions take precedence over project documents.
9
+ Keep current capability contracts separate from active changes and archived history.
10
+ See agents/AGENTS.md for lifecycle navigation and agents/SETUP.md for initial configuration.
11
+ For a broad or oversized request, use agents/prompts/intake.md before implementation.
12
+ <!-- sdd-flow:end -->
@@ -1,70 +1,16 @@
1
- # SDD Workflow - Quick Start
2
-
3
- ## Cycle
4
-
5
- Each feature goes through 4 phases in isolated sessions:
6
-
7
- ```
8
- RESEARCH → PLAN → IMPLEMENT → VALIDATE
9
- ```
10
-
11
- ## Initial setup
12
-
13
- After running `sdd init`, open your agent in the project and instruct:
14
-
15
- ```
16
- "Read and follow agents/SETUP.md"
17
- ```
18
-
19
- - **New project:** describe the project or provide the PRD — the agent generates PROJECT.md and the skills
20
- - **Existing project:** the agent scans the code automatically
21
-
22
- Review the generated files and delete `agents/SETUP.md`.
23
-
24
- ## Starting a feature
25
-
26
- ### With slash commands
27
-
28
- ```
29
- /sdd-research 001-feature-name → produces RESEARCH.md
30
- /sdd-plan 001-feature-name → produces SPEC.md + TASK.md + TEST.md
31
- /sdd-implement 001-feature-name → implements one task at a time
32
- /sdd-validate 001-feature-name → produces VALIDATION.md
33
- ```
34
-
35
- ### Without slash commands
36
-
37
- Instruct your agent in each session:
38
-
39
- ```
40
- "Read and follow agents/prompts/rpi-research.md. Spec: 001-feature-name"
41
- "Read and follow agents/prompts/rpi-plan.md. Spec: 001-feature-name"
42
- "Read and follow agents/prompts/rpi-implement.md. Spec: 001-feature-name"
43
- "Read and follow agents/prompts/rpi-validate.md. Spec: 001-feature-name"
44
- ```
45
-
46
- ## Creating a new spec
47
-
48
- ```bash
49
- sdd new feature-name
50
- # ✔ Spec created: agents/specs/001-feature-name/
51
- ```
52
-
53
- ## Spec structure after the full cycle
54
-
55
- ```
56
- agents/specs/001-feature-name/
57
- RESEARCH.md ← phase 1
58
- SPEC.md ← phase 2
59
- TASK.md ← phase 2
60
- TEST.md ← phase 2
61
- PROGRESS.md ← updated in phase 3
62
- DECISIONS.md ← architectural decisions
63
- VALIDATION.md ← phase 4
64
- ```
65
-
66
- ## References
67
-
68
- - Process rules → `agents/RULES.md`
69
- - Full workflow definition → `agents/AGENTS.md`
70
- - Documentation → https://github.com/moisesuailab/sdd-flow
1
+ # SDD Flow quick start
2
+
3
+ 1. Complete agents/SETUP.md and run sdd doctor.
4
+ 2. Create a change: sdd new feature-name --mode standard.
5
+ 3. Follow agents/prompts/rpi-plan.md; use Research first when uncertainty warrants it.
6
+ 4. Run sdd check ID. Review the scope and record actual authorization: sdd approve ID --by NAME.
7
+ 5. Resume with sdd context ID --phase implement --task T01. Keep task state in TASK.md front matter.
8
+ 6. Run sdd verify ID --scope partial for early feedback.
9
+ 7. Consolidate affected current contracts, finish tasks and run full verification.
10
+ 8. Close after review: sdd close ID --by NAME --archive. Add --note when no lasting contract changed.
11
+
12
+ Manual/inspection acceptance: create a version-bound template with sdd evidence ID.
13
+ Execute the scenarios, record results, executor, timestamp and notes, then run
14
+ sdd verify ID --evidence agents/specs/ID/EVIDENCE.json.
15
+
16
+ Use sdd help for commands and sdd update --dry-run before upgrading customized workflows.