82 lines
6.7 KiB
JavaScript
82 lines
6.7 KiB
JavaScript
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { execFileSync } from 'node:child_process';
|
|
import { createHash, randomUUID } from 'node:crypto';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { inflateRawSync } from 'node:zlib';
|
|
|
|
// Export the committed program. No running host, user data directory, installed
|
|
// application, credentials, build output or historical evidence is consulted.
|
|
const directories = ['src', 'public', 'scripts', 'tests', 'examples', 'benchmarks', 'research', 'licenses'];
|
|
const files = ['package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'index.html', 'mobile.html',
|
|
'.gitignore', '.gitattributes', 'README.md', 'CHANGELOG.md', 'DESIGN.md', 'AGENTS.md', 'THIRD_PARTY_NOTICES.txt',
|
|
'Start-Workbench.cmd', 'Stop-Workbench.cmd', 'Start-Desktop.cmd'];
|
|
files.push('.gitea/workflows/ci.yml');
|
|
const guide = name => /^docs\/[^/]+\.md$/.test(name) || /^docs\/research\/[^/]+\.(?:md|json)$/.test(name);
|
|
|
|
function archivedFiles(file) {
|
|
const buffer = fs.readFileSync(file), end = buffer.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06]));
|
|
if (end < 0) throw new Error('Source ZIP directory is missing.');
|
|
const count = buffer.readUInt16LE(end + 10), result = new Map(); let offset = buffer.readUInt32LE(end + 16);
|
|
for (let index = 0; index < count; index++) {
|
|
if (buffer.readUInt32LE(offset) !== 0x02014b50) throw new Error('Invalid source ZIP entry.');
|
|
const length = buffer.readUInt16LE(offset + 28), name = buffer.subarray(offset + 46, offset + 46 + length).toString('utf8');
|
|
const local = buffer.readUInt32LE(offset + 42), start = local + 30 + buffer.readUInt16LE(local + 26) + buffer.readUInt16LE(local + 28);
|
|
const compressed = buffer.subarray(start, start + buffer.readUInt32LE(offset + 20)), method = buffer.readUInt16LE(offset + 10);
|
|
if (![0, 8].includes(method) || result.has(name)) throw new Error('Unsupported or duplicate source ZIP entry.');
|
|
const bytes = method === 8 ? inflateRawSync(compressed) : compressed;
|
|
if (bytes.length !== buffer.readUInt32LE(offset + 24)) throw new Error('Source ZIP entry length mismatch.');
|
|
if (!name.endsWith('/')) result.set(name, bytes);
|
|
offset += 46 + length + buffer.readUInt16LE(offset + 30) + buffer.readUInt16LE(offset + 32);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export function packageSource({ root = process.cwd(), outputRoot = path.join(root, 'releases') } = {}) {
|
|
root = path.resolve(root); outputRoot = path.resolve(outputRoot);
|
|
const git = args => execFileSync('git', args, { cwd: root, windowsHide: true, maxBuffer: 32 * 1024 * 1024 });
|
|
const sourceCommit = git(['rev-parse', 'HEAD']).toString().trim();
|
|
const version = JSON.parse(git(['show', sourceCommit + ':package.json'])).version;
|
|
if (!/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/i.test(version)) throw new Error('Invalid committed program version.');
|
|
const selectedPaths = git(['ls-tree', '-r', '--name-only', '-z', sourceCommit]).toString('utf8').split('\0').filter(name =>
|
|
files.includes(name) || directories.some(directory => name.startsWith(directory + '/')) || guide(name));
|
|
const roots = [...directories.filter(name => selectedPaths.some(file => file.startsWith(name + '/'))),
|
|
...files.filter(name => selectedPaths.includes(name)), ...selectedPaths.filter(guide)];
|
|
const tree = git(['ls-tree', '-r', '--long', '-z', sourceCommit, '--', ...roots]).toString('utf8').split('\0').filter(Boolean).map(line => {
|
|
const match = /^(\d+) (\w+) ([a-f0-9]+)\s+(\d+|-)\t([\s\S]+)$/.exec(line);
|
|
if (!match) throw new Error('Invalid committed source entry.');
|
|
return { mode: match[1], type: match[2], gitBlob: match[3], bytes: Number(match[4]), path: match[5] };
|
|
});
|
|
const entries = tree.filter(row => files.includes(row.path) || directories.some(name => row.path.startsWith(name + '/')) || guide(row.path));
|
|
if (!entries.some(row => row.path === 'package-lock.json') || !entries.some(row => row.path.startsWith('src/'))) throw new Error('Committed source and dependency lock are required.');
|
|
if (entries.some(row => row.type !== 'blob' || !['100644', '100755'].includes(row.mode))) throw new Error('Source release requires regular committed files, without links or submodules.');
|
|
const name = `Agent-Workbench-${version}-source-code-${sourceCommit.slice(0, 8)}-${randomUUID()}`;
|
|
fs.mkdirSync(outputRoot, { recursive: true });
|
|
const archive = path.join(outputRoot, name + '.zip'), fd = fs.openSync(archive, 'wx');
|
|
try { execFileSync('git', ['archive', '--format=zip', '--prefix=Agent-Workbench-' + version + '-source/', sourceCommit, '--', ...roots], { cwd: root, windowsHide: true, stdio: ['ignore', fd, 'pipe'] }); }
|
|
finally { fs.closeSync(fd); }
|
|
const archived = archivedFiles(archive), prefix = 'Agent-Workbench-' + version + '-source/';
|
|
if (archived.size !== entries.length) throw new Error('Source ZIP file scope differs from the selected committed tree.');
|
|
const exported = entries.map(row => {
|
|
const bytes = archived.get(prefix + row.path); if (!bytes) throw new Error('Committed source missing from ZIP: ' + row.path);
|
|
return { path: row.path, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex'), gitBytes: row.bytes, gitBlob: row.gitBlob };
|
|
});
|
|
const result = { kind: 'source-code', version, sourceCommit, sourceTree: git(['rev-parse', sourceCommit + '^{tree}']).toString().trim(),
|
|
path: archive, bytes: fs.statSync(archive).size, sha256: createHash('sha256').update(fs.readFileSync(archive)).digest('hex'),
|
|
createdAt: new Date().toISOString(), files: exported, archiveAttributes: 'git archive applies committed .gitattributes, including CRLF for Windows launch scripts; bytes/sha256 identify exported ZIP bytes, gitBytes/gitBlob identify original committed blobs.',
|
|
scope: 'Committed program, build scripts, tests, .gitea/workflows/ci.yml, examples, dependency lock, licenses and text guides. No user projects, sessions, API credentials, installed runtimes or historical evidence archives. Build with Node 24, npm ci and npm run build. Historical acceptance drivers may require separately retained evidence or external engines.' };
|
|
fs.writeFileSync(path.join(outputRoot, name + '.json'), JSON.stringify(result, null, 2) + '\n', { flag: 'wx' });
|
|
return result;
|
|
}
|
|
|
|
export { archivedFiles as readSourceZip };
|
|
|
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
const args = process.argv.slice(2);
|
|
if (args.length === 1 && args[0] === '--help') console.log('node scripts/package-source.mjs — ZIP of committed program source only; no running Workbench, build, installation or user data required.');
|
|
else {
|
|
if (args.length) throw new Error('Use --help.');
|
|
const result = packageSource(); console.log(JSON.stringify({ ...result, files: result.files.length }, null, 2));
|
|
}
|
|
}
|