teimmo 0.0.0-stage → 0.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/artifacts.mjs ADDED
@@ -0,0 +1,232 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { spawnSync } from 'node:child_process';
5
+ import {validateEvidence} from './evidence.mjs';
6
+
7
+ export const digest = value => createHash('sha256').update(value).digest('hex');
8
+ export function assert(condition, message) {
9
+ if (!condition) throw new Error(message);
10
+ }
11
+ export function readJson(file) {
12
+ return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
13
+ }
14
+ export function write(file, text) {
15
+ fs.mkdirSync(path.dirname(file), { recursive: true });
16
+ const temporary = file + '.' + randomUUID() + '.tmp';
17
+ try {
18
+ fs.writeFileSync(temporary, text, { flag: 'wx' });
19
+ for(let attempt=0;;attempt++){
20
+ try{fs.renameSync(temporary,file);break;}
21
+ catch(error){
22
+ if(process.platform!=='win32'||!['EPERM','EACCES','EBUSY'].includes(error.code)||attempt>=4)throw error;
23
+ // A short-lived Windows reader can prevent atomic replacement of an open file.
24
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25*(attempt+1));
25
+ }
26
+ }
27
+ } finally {
28
+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
29
+ }
30
+ }
31
+ export function relativeFile(root, name) {
32
+ assert(typeof name === 'string' && name.length > 0 && !path.isAbsolute(name), 'Expected relative file path');
33
+ assert(!/[\\:\x00-\x1f]/.test(name), 'Use forward slashes in file paths');
34
+ const parts = name.split('/');
35
+ assert(parts.every(part => part && part !== '.' && part !== '..' && !/[. ]$/.test(part)), 'Invalid path segment');
36
+ assert(parts.every(part => !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(part)), 'Reserved Windows filename');
37
+ let target = root;
38
+ for (const part of parts) {
39
+ target = path.join(target, part);
40
+ const stat = fs.lstatSync(target, { throwIfNoEntry: false });
41
+ assert(!stat?.isSymbolicLink(), 'Symlink destination refused: ' + name);
42
+ }
43
+ return target;
44
+ }
45
+ export function inventory(root) {
46
+ const git = spawnSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], {
47
+ cwd: root, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024
48
+ });
49
+ assert(git.status === 0, 'Git inventory failed');
50
+ return [...new Set(git.stdout.split('\0').filter(Boolean))].sort()
51
+ .filter(name => !name.startsWith('.harness/'));
52
+ }
53
+ export function snapshot(root) {
54
+ const names = inventory(root);
55
+ // Approved documents remain covered even when a repository ignores them.
56
+ const specs = path.join(root, 'harness-spec');
57
+ if (fs.existsSync(specs)) {
58
+ for (const name of fs.readdirSync(specs)) names.push('harness-spec/' + name);
59
+ }
60
+ return digest([...new Set(names)].sort().map(name => {
61
+ const file = relativeFile(root, name);
62
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
63
+ if (!stat) return name + ':deleted';
64
+ assert(stat.isFile(), 'Snapshot currently requires ordinary files: ' + name);
65
+ return name + ':' + (stat.mode & 0o111) + ':' + digest(fs.readFileSync(file));
66
+ }).join('\n'));
67
+ }
68
+ export function contractDigest(root) {
69
+ const files=['brief.md', 'requirements.md', 'design.md', 'tasks.md', 'checks.json', 'traceability.json'];
70
+ for(const name of ['domain.json','obligations.json'])if(fs.existsSync(path.join(root,'harness-spec',name)))files.push(name);
71
+ return digest(files
72
+ .map(name => name + ':' + digest(fs.readFileSync(path.join(root, 'harness-spec', name)))).join('\n'));
73
+ }
74
+ export function testDigest(root, checks) {
75
+ return digest([...new Set(checks.flatMap(check => check.files))].sort()
76
+ .map(name => name + ':' + digest(fs.readFileSync(relativeFile(root, name)))).join('\n'));
77
+ }
78
+ export function analyze(root) {
79
+ const folder = path.join(root, 'harness-spec');
80
+ for (const name of ['brief.md', 'requirements.md', 'design.md', 'tasks.md']) {
81
+ assert(fs.readFileSync(path.join(folder, name), 'utf8').trim().length > 20, 'Missing content in ' + name);
82
+ }
83
+ const checks = readJson(path.join(folder, 'checks.json'));
84
+ assert(Array.isArray(checks) && checks.length > 0, 'Acceptance commands required');
85
+ const checkIds = new Set();
86
+ for (const check of checks) {
87
+ assert(typeof check.id === 'string' && /^[\w-]+$/.test(check.id) && !checkIds.has(check.id), 'Check ID must be unique');
88
+ checkIds.add(check.id);
89
+ validateEvidence(check);
90
+ assert(Array.isArray(check.argv) && check.argv.length && check.argv.every(x => typeof x === 'string' && x.length), 'Check argv required');
91
+ assert(Array.isArray(check.files) && check.files.length > 0, 'Acceptance file list required');
92
+ for (const name of check.files) assert(fs.statSync(relativeFile(root, name)).isFile(), 'Acceptance file missing');
93
+ // Static test-path literals are evidence dependencies, not editable product source.
94
+ const referenced=[...check.argv];
95
+ for(const name of check.files){
96
+ const text=fs.readFileSync(relativeFile(root,name),'utf8');
97
+ for(const match of text.matchAll(/["'`]([A-Za-z0-9_./\\-]+\.[A-Za-z0-9_-]+)["'`]/g)){
98
+ referenced.push(match[1]);
99
+ referenced.push(path.relative(root,path.resolve(root,path.dirname(name),match[1])).replaceAll('\\','/'));
100
+ }
101
+ }
102
+ for(const ref of referenced){
103
+ const name=ref.replaceAll('\\','/').replace(/^\.\//,'');
104
+ if(!/^(tests|acceptance)\//.test(name)||name.split('/').includes('..'))continue;
105
+ const file=relativeFile(root,name);
106
+ if(fs.existsSync(file)&&fs.statSync(file).isFile())assert(check.files.includes(name),'Unfrozen test dependency: '+name+' required by '+check.id+'; include runner, assertions and local helpers in check.files');
107
+ }
108
+ assert(check.timeoutMs === undefined || Number.isInteger(check.timeoutMs) && check.timeoutMs > 0 && check.timeoutMs <= 3600000, 'Invalid test timeout');
109
+ }
110
+ const trace = readJson(path.join(folder, 'traceability.json'));
111
+ assert(Array.isArray(trace.criteria) && trace.criteria.length > 0 && trace.criteria.every(id => typeof id === 'string' && /^AC-\d+$/.test(id)), 'criteria must list AC IDs');
112
+ assert(new Set(trace.criteria).size === trace.criteria.length, 'Duplicate criterion');
113
+ const markdownIds = new Set(fs.readFileSync(path.join(folder, 'requirements.md'), 'utf8').match(/\bAC-\d+\b/g) || []);
114
+ assert(trace.criteria.every(id => markdownIds.has(id)) && [...markdownIds].every(id => trace.criteria.includes(id)), 'Traceability and requirements must contain the same AC IDs');
115
+ assert(Array.isArray(trace.tasks) && trace.tasks.length > 0, 'Tasks required in traceability');
116
+ const taskIds = new Set();
117
+ const taskText = fs.readFileSync(path.join(folder, 'tasks.md'), 'utf8');
118
+ for (const task of trace.tasks) {
119
+ assert(typeof task.id === 'string' && /^T-\d+$/.test(task.id) && !taskIds.has(task.id), 'Unique T-number task IDs required');
120
+ assert(new RegExp('\\b' + task.id + '\\b').test(taskText), 'Task ID absent from tasks.md: ' + task.id);
121
+ taskIds.add(task.id);
122
+ assert(Array.isArray(task.criteria) && task.criteria.length && task.criteria.every(id => trace.criteria.includes(id)), 'Task criterion references invalid');
123
+ assert(Array.isArray(task.dependsOn), 'dependsOn array required');
124
+ if(task.files!==undefined){assert(Array.isArray(task.files)&&task.files.length,'Task files required');task.files.forEach(name=>relativeFile(root,name));}
125
+ if(task.checks!==undefined){
126
+ assert(Array.isArray(task.checks)&&task.checks.length&&task.checks.every(id=>checkIds.has(id)),'Invalid task checks');
127
+ assert(task.criteria.every(ac=>task.checks.some(id=>checks.find(c=>c.id===id)?.evidence?.tests.some(t=>t.criteria.includes(ac)))),'Task checks do not cover its criteria');
128
+ }
129
+ }
130
+ const declaredTasks = new Set(taskText.match(/\bT-\d+\b/g) || []);
131
+ assert([...declaredTasks].every(id => taskIds.has(id)), 'tasks.md contains an unmapped task');
132
+ const visited = new Set(), active = new Set(), order = [];
133
+ function visit(id) {
134
+ assert(taskIds.has(id), 'Unknown task dependency: ' + id);
135
+ assert(!active.has(id), 'Task dependency cycle at ' + id);
136
+ if (visited.has(id)) return;
137
+ active.add(id);
138
+ for (const dependency of trace.tasks.find(task => task.id === id).dependsOn) visit(dependency);
139
+ active.delete(id);
140
+ visited.add(id);
141
+ order.push(id);
142
+ }
143
+ for (const id of taskIds) visit(id);
144
+ assert(Array.isArray(trace.coverage), 'coverage array required');
145
+ const coverage = trace.criteria.map(id => {
146
+ const row = trace.coverage.find(item => item.criterion === id);
147
+ assert(row && Array.isArray(row.checks) && row.checks.length && row.checks.every(check => checkIds.has(check)), 'Missing or invalid test mapping for ' + id);
148
+ assert(row.checks.some(checkId=>checks.find(c=>c.id===checkId)?.evidence?.tests.some(t=>t.criteria.includes(id))), 'Missing named test mapping for ' + id);
149
+ const tasks = trace.tasks.filter(task => task.criteria.includes(id)).map(task => task.id);
150
+ assert(tasks.length > 0, 'Criterion has no implementation task: ' + id);
151
+ return { criterion: id, tasks, checks: row.checks };
152
+ });
153
+ assert(trace.coverage.length === trace.criteria.length, 'Duplicate or extra coverage mapping');
154
+ for(const check of checks)for(const test of check.evidence?.tests||[])assert(test.criteria.every(id=>trace.criteria.includes(id)), 'Test references unknown criterion');
155
+ return { checks, trace, coverage, order };
156
+ }
157
+ export function applyFiles(root, stage, files, frozen = []) {
158
+ assert(Array.isArray(files), 'files must be an array');
159
+ const required = {
160
+ discussion: ['harness-spec/brief.md'],
161
+ requirements: ['harness-spec/requirements.md'],
162
+ design: ['harness-spec/design.md'],
163
+ tasks: ['harness-spec/tasks.md', 'harness-spec/checks.json'],
164
+ analysis: ['harness-spec/traceability.json', 'harness-spec/analysis.md']
165
+ };
166
+ for (const name of required[stage] || []) assert(files.some(file => file.path === name), 'Missing proposed artifact: ' + name);
167
+ const seen = new Set();
168
+ const allowed = {
169
+ discussion: ['harness-spec/brief.md'],
170
+ requirements: ['harness-spec/requirements.md'],
171
+ design: ['harness-spec/design.md'],
172
+ analysis: ['harness-spec/traceability.json', 'harness-spec/analysis.md']
173
+ };
174
+ const entries = files.map(file => {
175
+ assert(typeof file.content === 'string', 'Each proposal needs full text content');
176
+ const name = file.path;
177
+ const destination = relativeFile(root, name);
178
+ const folded = name.toLowerCase();
179
+ assert(!seen.has(folded), 'Duplicate file proposal');
180
+ seen.add(folded);
181
+ assert(!['.git', '.harness'].some(prefix => folded === prefix || folded.startsWith(prefix + '/')), 'Protected path');
182
+ assert(!['review-spec', 'review-quality'].includes(stage), 'Reviews cannot change files');
183
+ if (allowed[stage]) assert(allowed[stage].includes(name)||name==='harness-spec/domain.json', 'Unexpected ' + stage + ' file: ' + name);
184
+ if (['implementation', 'repair'].includes(stage)) {
185
+ assert(!folded.startsWith('harness-spec/') && !frozen.some(item => item.toLowerCase() === folded), 'Frozen acceptance contract');
186
+ }
187
+ if (stage === 'tasks') {
188
+ assert(name === 'harness-spec/tasks.md' || name === 'harness-spec/checks.json' || name==='harness-spec/domain.json' ||
189
+ name.startsWith('tests/') || name.startsWith('acceptance/'), 'Planning may create only tasks, checks and acceptance test files');
190
+ if (!name.startsWith('harness-spec/')) assert(!fs.existsSync(destination)||fs.readFileSync(destination,'utf8')===file.content, 'Use a new acceptance test file; preserve existing tests');
191
+ }
192
+ const existed = fs.existsSync(destination);
193
+ assert(!existed || fs.statSync(destination).isFile(), 'Destination is not a file');
194
+ return { destination, content: file.content, previous: existed ? fs.readFileSync(destination) : null };
195
+ });
196
+ // Roll back ordinary write errors. A process crash is recovered via the persisted journal.
197
+ const journal = path.join(root, '.harness', 'pending-writes.json');
198
+ write(journal, JSON.stringify(entries.map(entry => ({
199
+ path: path.relative(root, entry.destination).replaceAll('\\', '/'),
200
+ previous: entry.previous?.toString('base64') ?? null,
201
+ proposedHash: digest(Buffer.from(entry.content))
202
+ }))));
203
+ try {
204
+ for (const entry of entries) write(entry.destination, entry.content);
205
+ } catch (error) {
206
+ recoverWrites(root);
207
+ throw error;
208
+ }
209
+ fs.unlinkSync(journal);
210
+ }
211
+ export function recoverWrites(root) {
212
+ const journal = path.join(root, '.harness', 'pending-writes.json');
213
+ if (!fs.existsSync(journal)) return;
214
+ const entries=readJson(journal);
215
+ assert(Array.isArray(entries),'Invalid recovery journal');
216
+ // Check the entire batch before rollback so a conflict leaves all evidence intact.
217
+ for (const entry of entries) {
218
+ assert(!['.git', '.harness'].some(prefix => entry.path.toLowerCase() === prefix || entry.path.toLowerCase().startsWith(prefix + '/')), 'Invalid recovery journal');
219
+ const file = relativeFile(root, entry.path);
220
+ const exists=fs.existsSync(file),old=entry.previous===null?null:digest(Buffer.from(entry.previous,'base64'));
221
+ const actual=exists?digest(fs.readFileSync(file)):null;
222
+ assert(entry.proposedHash&&/^[a-f0-9]{64}$/.test(entry.proposedHash)||actual===old,'Recovery conflict: legacy journal cannot establish file ownership: '+entry.path+'. Preserve edits and inspect the journal before recovery.');
223
+ assert(actual===old||actual===entry.proposedHash,'Recovery conflict: file changed after interrupted write: '+entry.path+'. Preserve edits and inspect the journal before recovery.');
224
+ }
225
+ for (const entry of entries) {
226
+ const file=relativeFile(root,entry.path);
227
+ if (entry.previous === null) {
228
+ if (fs.existsSync(file)) fs.unlinkSync(file);
229
+ } else write(file, Buffer.from(entry.previous, 'base64'));
230
+ }
231
+ fs.unlinkSync(journal);
232
+ }