feat(ci): verify clean source builds and pinned official contracts

This commit is contained in:
Agent Workbench Dev
2026-11-07 21:53:43 +08:00
parent a43262c112
commit af42b949ef
20 changed files with 4376 additions and 7 deletions
+46
View File
@@ -0,0 +1,46 @@
name: Official contracts and Windows source CI
on:
push:
branches: [feat/task-agreement-1.25, main]
pull_request:
workflow_dispatch:
jobs:
windows-source:
runs-on: awb-windows-x64
permissions:
contents: read
actions: write
steps:
- name: Check out committed source
uses: https://gitea.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
fetch-depth: 1
persist-credentials: false
- name: Pin Node and bundled npm
uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version: 24.22.1
check-latest: false
- name: Pin the base QA Python
uses: https://github.com/actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
with:
python-version: 3.11.15
check-latest: false
- name: Fresh dependencies, contracts, build, tests and owned Windows smoke
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$qaPython = (Get-Command python.exe -ErrorAction Stop).Source
$qaNode = (Get-Command node.exe -ErrorAction Stop).Source
& $qaNode scripts/ci.mjs --profile windows --python $qaPython --output-root .qa/ci
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Preserve original reports and failures
if: always()
uses: https://gitea.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5
with:
name: windows-source-ci
path: .qa/ci/**/evidence/**
if-no-files-found: error
retention-days: 14
+31
View File
@@ -0,0 +1,31 @@
# 可重复的源码与官方契约 CI
当前入口从已提交 Git HEAD 导出新的源码 ZIP,逐源文件核 SHA,展开到唯一目录后实际 `npm ci`。不复用工作区 `node_modules` 或 junction,不读取用户项目、运行服务、模型 Key/配置或旧实验。可审查源码改动应先提交;文档/其他非编译改动会在报告记录,不参与程序构建。
环境固定于 `scripts/ci-environment.json`:Node 24.22.1、随包 npm 11.19.1;Windows 全套另需 Python 3.11.15。pytest 8.4.2、pip 与全部框架依赖通过 `scripts/ci-python-requirements.txt` 精确 wheel SHA 安装到本次新 venv。Playwright 1.64.1、Electron 45.2.0 和其余 npm 输入由 lock 固定。缺环境、版本不同、依赖安装或实际测试失败均非零退出。
```powershell
& 'D:/Ai-project/REA逆向/tools/node-v24.22.1-win-x64/node.exe' scripts/ci.mjs --profile contract
& 'D:/Ai-project/REA逆向/tools/node-v24.22.1-win-x64/node.exe' scripts/ci.mjs --profile windows --python '绝对路径/python.exe'
```
其他开发机使用自身已核对的相同版本 Node 路径。npm 入口为 `npm run ci:contract` / `npm run ci:windows -- --python ...`。默认输出 `.qa/ci/run-.../evidence/report.json`,可用 `--output-root` 指定;每次新建目录,旧失败/日志不覆盖。数据/依赖/缓存位于同 run 的独立目录,不作为发布源码或 CI 证据上传。
| 范围 | 实际执行与判定 |
| --- | --- |
| contract | 四来源清单原字节、注册表及请求默认版本/字段/弃用快照、14指定行为回归和 CI/源码包专项;完整应用构建。可在支持 Node 的平台执行,当前其他平台实测状态另列。 |
| windows | 上述来源/构建与全部 `.test.mjs`,实际 Edge 必需;本次安装 Chromium 后执行网页及隐藏 Electron 1280/390 冒烟。安装/回退相关回归使用自有隔离 fixture,不接触正式服务。 |
Node TAP 的失败、取消、跳过、todo、缺完整统计或零测试均不能判定通过,不能通过删 Python/浏览器测试掩盖环境缺项。每条命令保存所属 PID、完整 argv、真实 exit/signal、原 stdout/stderr 字节及 SHA;源码和全部编译工件在结束后再次核对。网页/Electron 原截图、DOM、错误与所属关闭状态另存。
GitAtlas 工作流为 `.gitea/workflows/ci.yml`,push / pull_request / 手工触发。Gitea 1.26.2 与仓库 Actions 已公开核实;运行/runner API 匿名 401,**可用执行器及远端运行尚未确认**。工作流要求独立 Windows x64 runner 标签 `awb-windows-x64:host`、PowerShell、Git、Edge及 action 所需 Node 16/20 执行能力,随后 action 安装固定 Node/Python。不会在正式电脑自动安装持久 runner。Action 均固定完整 commit,Checkout 同 commit 使用 Gitea 官方镜像;原 GitHub 网络失败完整保留。证据上传使用 Gitea actions v3 固定契约,实际上传与远端执行需要真实 job 回执。
官方更新先保留原响应/失败/SHA,修改注册表和对应行为回归,再生成新快照、审查差异并追加 `tests/fixtures/official-contracts/INDEX.json` 的 history;旧快照保留。`--freeze` 只冻结,不能当作通过。命令:
```text
node scripts/verify-official-contracts.mjs --freeze NEW_SNAPSHOT.json
node scripts/verify-official-contracts.mjs --diff OLD_SNAPSHOT.json NEW_SNAPSHOT.json --output NEW_DIFF.json
node scripts/verify-official-contracts.mjs --output NEW_VERIFICATION.json
```
同型号的协议/API版本分别成键,字段来源、缓存/状态、弃用/别名、认证及新旧默认的差异会出现在报告;实际事实或请求默认变更不增加相应版本会失败。所有检查离线使用已固定官方原件,本机 HTTP/源码结果不等同真实官方/代理兼容、模型自主工程、缓存或 Purge 收益。M3 实际 schema2 迁移增量和新处理器产出后的回退仍另验,正式发行尚未发生。
+4 -3
View File
@@ -3,9 +3,9 @@
2026-11-07,基线 `470d694831c315c034e3f36891e4f3faf94cbe0f`,分支 `feat/task-agreement-1.25`,干净工作树。承接 I09/I11 已封存交付,不重做上一批。完成 I27 可重复的源码/契约/构建/安装检查入口与 I28 官方来源、版本差异及弃用的回归关联;随后 M3 单独冻结统一发行。
1. [complete] 固定470d6948基线/tree/锁文件/Node身份,planning catchup退出0。GitAtlas实际1.26.2且Actions启用,runner/runs匿名401,未确认执行器;1.26官方三篇HTTP200原件与重定向/401保存,见[来源](CI-SOURCES.md)。当前外部Python3.11.15缺pytest,缺环境失败原件保留。
2. [in_progress] 实现锁定依赖/前置环境/源码身份检查和唯一输出目录,接入官方注册表原件核对及契约、版本、弃用回归;缺环境和实际失败必须非零退出。
3. [pending] 建立 GitAtlas 工作流和可复用本地入口,区分可移植契约与 Windows 桌面/安装验证;检查源码包是否包含 CI 配置并用真实自有 Git ZIP 验证。
4. [pending] 在独立干净源码与实际新装依赖环境执行,记录 Node/Python/Playwright/Electron 身份、原命令/失败/构建及测试结果;不以原 node_modules junction 冒充干净安装,不将本地结果称远端执行。
2. [complete] 唯一run/原日志/exit/PID/环境、源码ZIP前后SHA、固定Node/npm/Python及带哈希venv依赖、官方四来源清单/26记录/版本字段弃用差异与14回归输入已实现。新专项和源码包最终11/11,首10/11保留;来源SHA/省略凭据getter/unknown命令/跳过不能改绿的边界通过。尚不替代独立干净环境结果。
3. [complete] `.gitea/workflows/ci.yml` 与本地contract/windows入口、真正YAML解析与固定action refs已实现;精确该workflow路径进入源码包白名单,实际自有Git ZIP和其它.gitea配置排除通过。实际Windows网页/隐藏Electron入口1280/390与关闭核对准备,独立运行尚待。
4. [in_progress] 在独立干净源码与实际新装依赖环境执行,记录 Node/Python/Playwright/Electron 身份、原命令/失败/构建及测试结果;不以原 node_modules junction 冒充干净安装,不将本地结果称远端执行。
5. [pending] 分阶段回顾与限定提交,核对最终输入、官方原字节、进程归属及封存记录;普通增量推送并逐 SHA 核远端。外部 runner 配置缺项需在完成具体实现和本地验证后准确列出。
新证据只写 `.qa/m2-ci-2026-11-07/`,原 I10/I13/I15/I14/I09-I11 封存根只读。本批不委派、不读真实模型 Key、不请求真实模型、不操作正式配置/数据/安装/重启,不续旧实验或用户工程,不安装持久 runner。公开 GitAtlas API/官方资料仅作只读调查,失败与无法确认状态均保留。
@@ -24,3 +24,4 @@
- Checkout原metadata HTTPS首次fetch失败、第二次45秒超时、第三次公开Git clone连接被重置(128);第四次Gitea官方actions镜像按同一v4.2.2 commit取得HTTP200原metadata。四记录分开,不能称GitHub网络已恢复;工作流采用同commit镜像URL。
- YAML依赖准备器首相对import多退一级,实收ERR_MODULE_NOT_FOUND;原脚本保持,第二轮正确import成功,只新增yaml和根依赖声明两个lock条目。
- 官方快照首准备器把已有受控同级fixture引用误判为逃逸;原helper保存,改为整个固定`tests/fixtures`范围,仍逐原字节SHA核对,未改原SOURCE.json或来源正文。
- 首专项11项为10过1失败:新源码ZIP fixture未声明workflow的LF,实际Git archive按全局属性导出CRLF。保留原11项日志/测试,只为自有fixture明确声明与产品一致的workflow LF,再单独补验该文件。来源索引检查首.gitattributes工作文本CRLF与Git LF不一致,原字节保存后只规范该文本,14暂存原字节再核对通过。
+15 -1
View File
@@ -31,7 +31,8 @@
"esbuild": "^0.25.10",
"innosetup-compiler": "6.3.1",
"typescript": "^5.9.3",
"vite": "^7.1.12"
"vite": "^7.1.12",
"yaml": "2.8.1"
}
},
"node_modules/@babel/code-frame": {
@@ -3120,6 +3121,19 @@
"dev": true,
"license": "ISC"
},
"node_modules/yaml": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz",
"integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==",
"dev": true,
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
},
"engines": {
"node": ">= 14.6"
}
},
"node_modules/yargs": {
"version": "15.4.1",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
+5 -1
View File
@@ -11,6 +11,9 @@
"desktop": "powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/Start-Desktop.ps1",
"verify:desktop": "node scripts/verify-desktop-window.mjs",
"test": "node --test --test-concurrency=2 tests/*.test.mjs",
"ci:contract": "node scripts/ci.mjs --profile contract",
"ci:windows": "node scripts/ci.mjs --profile windows",
"verify:official-contracts": "node scripts/verify-official-contracts.mjs",
"verify:ui": "node scripts/verify-ui.mjs",
"verify:orven": "node scripts/verify-orven-ui.mjs",
"verify:appearance": "node scripts/verify-orven-appearance.mjs",
@@ -78,6 +81,7 @@
"esbuild": "^0.25.10",
"innosetup-compiler": "6.3.1",
"typescript": "^5.9.3",
"vite": "^7.1.12"
"vite": "^7.1.12",
"yaml": "2.8.1"
}
}
+4
View File
@@ -1,5 +1,9 @@
# 统一执行进度
I27/I28源码阶段最终专项11/11、官方四来源清单/26记录/14回归输入与workflow真正YAML检查通过;首10/11和两个来源辅助失败保持。工作流只打包精确ci.yml,不遍历.gitea其它配置。实现从已提交HEAD导出/新依赖/venv/原日志/源码及编译前后核对,缺环境/真实跳过非零退出,实际桌面冒烟已准备。限定提交后执行独立干净Windows全套,正式/真实模型/Key/旧工程不动。
I27/I28来源阶段本地提交完成:14输入逐Git/原字节与已知凭据签名核对,7官方CI来源/4 action ref/7 PyPI wheel固定。官方契约完整44来源/26记录/14回归文件首离线通过;快照首同级引用、原source-package LF与.gitattributes文本CRLF失败保持。新专项首10/11,9新CI/官方检查通过,源码ZIP fixture补明确LF后单独复验。统一入口和实际桌面/干净环境验证继续,尚未远端执行/发行/正式写入。
I27/I28阶段1来源固定:7份CI官方正文/action元数据、4 action逐commit的ls-remote、7个PyPI通用wheel精确SHA完成。Python准备器首Colorama标签与第二轮误认为并行响应已齐的失败保留,第三轮只补缺文件,未污染外部Python。Mnemo指定v1 README SHA一致,已写本地只读字段/接入依赖反馈,当前不接入/请求/回复源线程或混入CI提交。下一实现统一入口、官方规格差异与缺环境非零退出。
I27/I28调查2完成:基线tree cf362e31固定,GitAtlas匿名版本/仓库API成功,1.26.2且Actions启用,runner/runs均401;不提取账户token或安装runner。取得对应版本三官方正文,原重定向/失败完整记录。几次调查误猜测试/浏览器模块名和PowerShell通配符路径已保留为读取错误,后续只用rg实际文件列表;产品未修改。下一固定来源并实现可重复检查入口与官方更新回归。
+78
View File
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import { randomUUID } from 'node:crypto';
import { chromium, _electron } from 'playwright';
import { HostController } from '../src/core/desktop/host-controller.mjs';
import { observeWindowsProcess } from '../src/core/desktop/process-identity.mjs';
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
import { projectEnvironment } from '../src/core/process-environment.mjs';
import { openWorkbenchTool } from './ui-navigation.mjs';
import { fileDigest, writeNewJson } from './ci-utils.mjs';
const args=process.argv.slice(2);
if(args.includes('--help')) {console.log('node scripts/ci-desktop-smoke.mjs --evidence NEW_DIRECTORY — actual locked Chromium and hidden Electron against an owned new host/project. No model, external project, formal configuration or installation.');process.exit(0);}
if(args.length!==2 || args[0]!=='--evidence')throw new Error('Use --help');
assert.equal(process.platform,'win32');
const appRoot=process.cwd(),evidence=path.resolve(args[1]);fs.mkdirSync(evidence);
const ownedRoot=path.join(appRoot,'.qa','ci-smoke-'+randomUUID().slice(0,8)),dataRoot=path.join(ownedRoot,'data'),projectRoot=path.join(ownedRoot,'project');fs.mkdirSync(projectRoot,{recursive:true});
const original=Buffer.from('# Owned CI project\n\nSource retained while actual web and Electron entry paths are exercised.\n');
fs.writeFileSync(path.join(projectRoot,'README.md'),original,{flag:'wx'});
const reservation=net.createServer();await new Promise(resolve=>reservation.listen(0,'127.0.0.1',resolve));const port=reservation.address().port;await new Promise(resolve=>reservation.close(resolve));
const controller=new HostController({appRoot,dataRoot,port,nodePath:process.execPath,timeoutMs:60000});
const report={schemaVersion:1,passed:false,startedAt:new Date().toISOString(),ownedRoot,port,groups:[],screenshots:[],pageErrors:[],externalRequests:[],scope:'Actual isolated Chromium/Electron and owned source/data only; no model or formal installation.'};
let browser,application,electronPid,hostIdentity,stage='host-start';
const record=(name,detail={})=>report.groups.push({name,passed:true,...detail});
const watch=(page)=>{page.on('pageerror',error=>report.pageErrors.push(error.message));page.on('request',request=>{const url=new URL(request.url());if(['http:','https:'].includes(url.protocol) && !(url.hostname==='127.0.0.1' && Number(url.port)===port))report.externalRequests.push(request.url());});};
async function capture(page,mode,width,height){
const id=mode+'-'+width,file=path.join(evidence,id+'.png');
if(mode==='electron'){
await application.evaluate(({BrowserWindow},size)=>BrowserWindow.getAllWindows()[0].setContentSize(...size),[width,height]);
await page.waitForFunction(size=>innerWidth===size[0] && innerHeight===size[1],[width,height]);
const value=await application.evaluate(async({BrowserWindow})=>{const window=BrowserWindow.getAllWindows()[0];const [width,height]=window.getContentSize();const image=await window.capturePage({x:0,y:0,width,height},{stayHidden:true,stayAwake:true});return{base64:image.toPNG().toString('base64'),visible:window.isVisible(),size:image.getSize()};});
assert.equal(value.visible,false);assert.ok(value.size.width>0 && value.size.height>0);fs.writeFileSync(file,Buffer.from(value.base64,'base64'),{flag:'wx'});
}else{await page.setViewportSize({width,height});await page.screenshot({path:file,fullPage:false});}
writeNewJson(path.join(evidence,id+'.dom.json'),{title:await page.title(),width,height,html:await page.content(),overflow:await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth)});
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false,'Document overflows');
const bytes=fs.readFileSync(file);assert.equal(bytes.subarray(1,4).toString(),'PNG');assert.ok(bytes.length>1000);
report.screenshots.push({file,width,height,sha256:fileDigest(file),bytes:bytes.length});
}
async function userPath(page,mode,projectId){
watch(page);await page.locator('.connection.connected').waitFor({timeout:30000});assert.match(await page.title(),/Orven/i);
await page.getByRole('combobox',{name:'当前项目',exact:true}).selectOption(projectId);
record(mode+' project selection and connected build');
await openWorkbenchTool(page,'打开模型中心');await page.getByRole('dialog',{name:'模型中心',exact:true}).waitFor();
await capture(page,mode,1280,900);await page.keyboard.press('Escape');
if(mode==='electron')await application.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].setContentSize(390,844));else await page.setViewportSize({width:390,height:844});
await openWorkbenchTool(page,'打开模型中心');await page.getByRole('dialog',{name:'模型中心',exact:true}).waitFor();
await capture(page,mode,390,844);await page.keyboard.press('Escape');
record(mode+' actual model center at 1280 and 390');
}
try{
hostIdentity=(await controller.start()).identity;report.host={pid:hostIdentity.pid,createdAt:hostIdentity.createdAt};
const project=await controller.api('/projects',{method:'POST',input:{root:projectRoot}}),session=await controller.api('/sessions',{method:'POST',input:{projectId:project.id}});
record('owned new host/project/session',{projectId:project.id,sessionId:session.id});
stage='chromium';browser=await chromium.launch({headless:true});report.chromiumVersion=browser.version();
const page=await browser.newPage({viewport:{width:1280,height:900}});watch(page);await page.goto(controller.url);await userPath(page,'web',project.id);await browser.close();browser=null;
stage='electron';const executable=desktopExecutableIdentity(appRoot).path;
application=await _electron.launch({executablePath:executable,args:[path.join(appRoot,'dist-desktop/main.cjs'),'--app-root',appRoot,'--data-root',dataRoot,'--node',process.execPath,'--port',String(port),'--hidden-window'],cwd:appRoot,env:projectEnvironment(),timeout:60000});
electronPid=await application.evaluate(()=>process.pid);report.electron={pid:electronPid,executable,sha256:fileDigest(executable),version:await application.evaluate(()=>process.versions.electron)};
const window=await application.firstWindow();await userPath(window,'electron',project.id);
const status=await controller.status();assert.equal(status.identity.pid,hostIdentity.pid);assert.ok(status.desktopWindows.entries.some(entry=>entry.pid===electronPid));
record('same owned host and actual registered Electron');
const center=await controller.api('/model-center');assert.equal(center.attempts.length,0,'No model request is permitted in CI smoke');
assert.deepEqual(fs.readFileSync(path.join(projectRoot,'README.md')),original);assert.deepEqual(report.pageErrors,[]);assert.deepEqual(report.externalRequests,[]);
record('original source retained; zero model attempts or outside page requests');
report.passed=true;
}catch(error){report.failure={stage,name:error.name,message:error.message,stack:error.stack};process.exitCode=1;}
finally{
try{if(browser)await browser.close();if(application)await application.close();
if(await controller.health())report.hostStop=await controller.stop();
const deadline=Date.now()+15000;while(electronPid && observeWindowsProcess(electronPid) && Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,100));
assert.equal(electronPid?!!observeWindowsProcess(electronPid):false,false,'Owned Electron did not exit');assert.equal(await controller.health(),null,'Owned port still responds');
report.cleanup={hostExited:hostIdentity?observeWindowsProcess(hostIdentity.pid)===null:true,electronExited:electronPid?observeWindowsProcess(electronPid)===null:true,portClosed:true};
assert.equal(report.cleanup.hostExited,true);
}catch(error){report.passed=false;report.cleanupFailure={message:error.message,stack:error.stack};process.exitCode=1;}
report.finishedAt=new Date().toISOString();writeNewJson(path.join(evidence,'result.json'),report);console.log(JSON.stringify({passed:report.passed,groups:report.groups.length,screenshots:report.screenshots.length,report:path.join(evidence,'result.json'),failure:report.failure?.message,cleanupFailure:report.cleanupFailure?.message}));
}
+21
View File
@@ -0,0 +1,21 @@
{
"schemaVersion": 1,
"node": "24.22.1",
"npm": "11.19.1",
"python": "3.11.15",
"pytest": "8.4.2",
"pip": "25.3",
"playwright": "1.64.1",
"electron": "45.2.0",
"runnerLabel": "awb-windows-x64",
"profiles": {
"contract": "Pinned official sources, registry/version/deprecation regressions and full application build. No Windows/real-provider claim.",
"windows": "Fresh locked dependencies, full source tests without skips, Microsoft Edge, actual Chromium/Electron smoke and owned installation regressions. No formal installation or model request."
},
"actions": {
"checkout": "https://gitea.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683",
"setupNode": "https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020",
"setupPython": "https://github.com/actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065",
"uploadArtifact": "https://gitea.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5"
}
}
+8
View File
@@ -0,0 +1,8 @@
# Python 3.11.15 CI QA only. Exact universal wheels from PyPI; use --require-hashes --only-binary=:all:.
pytest==8.4.2 --hash=sha256:872f880de3fc3a5bdc88a11b39c9710c3497a547cfa9320bc3c5e62fbf272e79
iniconfig==2.3.0 --hash=sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12
packaging==25.0 --hash=sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484
pluggy==1.6.0 --hash=sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746
Pygments==2.19.2 --hash=sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b
colorama==0.4.6 --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6
pip==25.3 --hash=sha256:9655943313a94722b7774661c21049070f6bbb0a1516bf02f7c8d5d9201514cd
+128
View File
@@ -0,0 +1,128 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { spawn } from 'node:child_process';
import { readSourceZip } from './package-source.mjs';
export const digest = bytes => createHash('sha256').update(bytes).digest('hex');
export const fileDigest = file => digest(fs.readFileSync(file));
export const writeNewJson = (file, value) => fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' });
export function createCiRun(outputRoot, profile) {
assert.ok(['contract', 'windows'].includes(profile), 'Unknown CI profile');
const root = path.resolve(outputRoot), run = path.join(root, `run-${profile}-${Date.now().toString(36)}-${randomUUID().slice(0,8)}`);
fs.mkdirSync(root, { recursive: true }); fs.mkdirSync(run);
for (const directory of ['evidence', 'source', 'cache', 'tmp']) fs.mkdirSync(path.join(run, directory));
return { root: run, evidence: path.join(run, 'evidence'), source: path.join(run, 'source'), cache: path.join(run, 'cache'), tmp: path.join(run, 'tmp') };
}
// Read only named OS variables. Never enumerate credential values or forward
// model settings, npm user config, provider tokens or external-engine paths.
export function ciEnvironment(run, input = process.env, node = process.execPath) {
const allowed = ['PATH','PATHEXT','SystemRoot','SystemDrive','WINDIR','ComSpec','TEMP','TMP','USERPROFILE','HOMEDRIVE','HOMEPATH','APPDATA','LOCALAPPDATA','ProgramFiles','ProgramFiles(x86)','CommonProgramFiles','HOME','LANG','LC_ALL'];
const env = {};
for (const key of Object.keys(input)) if (allowed.some(name=>name.toLowerCase() === key.toLowerCase())) env[key] = input[key];
const inherited = Object.keys(env).find(key=>key.toLowerCase()==='path');
const originalPath = inherited ? env[inherited] : '';
if (inherited) delete env[inherited];
env.PATH = [path.dirname(node), originalPath].filter(Boolean).join(path.delimiter);
env.TEMP = run.tmp; env.TMP = run.tmp; env.CI = 'true'; env.PYTEST_DISABLE_PLUGIN_AUTOLOAD = '1';
const userConfig = path.join(run.root, 'npm-user.conf'), globalConfig = path.join(run.root, 'npm-global.conf');
for (const file of [userConfig, globalConfig]) if (!fs.existsSync(file)) fs.writeFileSync(file, '', { flag: 'wx' });
env.npm_config_userconfig = userConfig; env.npm_config_globalconfig = globalConfig;
env.npm_config_registry = 'https://registry.npmjs.org/'; env.npm_config_cache = path.join(run.cache, 'npm');
env.npm_config_audit = 'false'; env.npm_config_fund = 'false'; env.npm_config_update_notifier = 'false';
env.PLAYWRIGHT_BROWSERS_PATH = path.join(run.cache, 'playwright');
env.electron_config_cache = path.join(run.cache, 'electron');
return env;
}
export async function loggedCommand({ id, executable, args = [], cwd, env, evidence, timeoutMs = 0, check = true }) {
assert.match(id, /^[a-z0-9-]+$/);
const stdoutFile = path.join(evidence, `${id}.stdout.log`), stderrFile = path.join(evidence, `${id}.stderr.log`);
let stdoutFd = fs.openSync(stdoutFile, 'wx'), stderrFd = fs.openSync(stderrFile, 'wx');
const startedAt = new Date().toISOString(), started = Date.now();
let child, timer, interrupted = false, spawnError;
const terminate = () => {
interrupted = true;
if (!child?.pid) return;
if (process.platform === 'win32') {
const stop = spawn('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
stop.on('error', () => { try { child.kill(); } catch {} });
} else child.kill('SIGTERM');
};
const onInterrupt = () => terminate();
process.once('SIGINT', onInterrupt); process.once('SIGTERM', onInterrupt);
try {
const result = await new Promise(resolve => {
child = spawn(executable, args, { cwd, env, windowsHide: true, stdio: ['ignore', stdoutFd, stderrFd] });
child.once('spawn', () => writeNewJson(path.join(evidence, `${id}.started.json`), { id, executable, args, cwd, pid: child.pid, parentPid: process.pid, startedAt, environmentNames: Object.keys(env).sort() }));
child.once('error', error => { spawnError = { name: error.name, message: error.message, code: error.code }; });
child.once('close', (exitCode, signal) => resolve({ exitCode, signal }));
if (timeoutMs > 0) { timer = setTimeout(terminate, timeoutMs); timer.unref(); }
});
fs.closeSync(stdoutFd); stdoutFd = -1; fs.closeSync(stderrFd); stderrFd = -1;
const record = { id, executable, args, cwd, pid: child.pid ?? null, startedAt, finishedAt: new Date().toISOString(), durationMs: Date.now() - started, ...result, interrupted, spawnError: spawnError ?? null,
stdout: { file: stdoutFile, bytes: fs.statSync(stdoutFile).size, sha256: fileDigest(stdoutFile) }, stderr: { file: stderrFile, bytes: fs.statSync(stderrFile).size, sha256: fileDigest(stderrFile) } };
writeNewJson(path.join(evidence, `${id}.json`), record);
console.log(JSON.stringify({ command: id, exitCode: record.exitCode, interrupted, durationMs: record.durationMs, evidence }));
if (check && (record.exitCode !== 0 || record.signal || interrupted || spawnError)) throw Object.assign(new Error(`CI command failed: ${id}. Original logs: ${stdoutFile} and ${stderrFile}`), { record });
return record;
} finally {
clearTimeout(timer); process.removeListener('SIGINT', onInterrupt); process.removeListener('SIGTERM', onInterrupt);
// Spawn errors still produce original records; handles are closed above.
for (const fd of [stdoutFd, stderrFd]) if (fd >= 0) try { fs.closeSync(fd); } catch {}
}
}
export function unpackVerifiedSource(archive, destination) {
assert.ok(archive.kind === 'source-code' && /^[a-f0-9]{40}$/.test(archive.sourceCommit));
assert.equal(fileDigest(archive.path), archive.sha256, 'Source ZIP SHA changed');
const entries = readSourceZip(archive.path), prefix = `Agent-Workbench-${archive.version}-source/`;
assert.equal(entries.size, archive.files.length, 'Unexpected source archive entries');
const seen = new Set();
for (const file of archive.files) {
assert.ok(!seen.has(file.path), 'Duplicate source path'); seen.add(file.path);
assert.ok(!file.path.includes('\\') && !file.path.startsWith('/') && !file.path.split('/').some(segment=>segment==='..' || segment.includes(':')), 'Invalid source archive path');
const output = path.resolve(destination, file.path), bytes = entries.get(prefix + file.path);
assert.ok(output.startsWith(path.resolve(destination) + path.sep));
assert.ok(Buffer.isBuffer(bytes), `Missing archived input ${file.path}`);
assert.equal(bytes.length, file.bytes, file.path); assert.equal(digest(bytes), file.sha256, file.path);
fs.mkdirSync(path.dirname(output), { recursive: true }); fs.writeFileSync(output, bytes, { flag: 'wx' });
}
return verifySourceInputs(destination, archive.files);
}
export function verifySourceInputs(root, files) {
for (const file of files) {
const full = path.join(root, file.path); assert.ok(fs.lstatSync(full).isFile() && !fs.lstatSync(full).isSymbolicLink(), file.path);
assert.equal(fileDigest(full), file.sha256, `Source input changed: ${file.path}`);
}
return { passed: true, files: files.length, identity: 'exported ZIP bytes after committed .gitattributes, before and after actual dependency install/build/tests' };
}
export function builtFiles(root) {
const directories = ['dist-client','dist-server','dist-desktop'], files = [];
const walk = (relative) => {
for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true }).sort((a,b)=>a.name.localeCompare(b.name))) {
assert.equal(entry.isSymbolicLink(), false, 'Build output link');
const current = path.join(relative, entry.name);
if (entry.isDirectory()) walk(current);
else { assert.ok(entry.isFile()); const full = path.join(root, current); files.push({ file: current.split(path.sep).join('/'), bytes: fs.statSync(full).size, sha256: fileDigest(full) }); }
}
};
for (const directory of directories) { assert.ok(fs.statSync(path.join(root,directory)).isDirectory(), `Missing ${directory}`); walk(directory); }
return files;
}
export function tapTotals(text) {
const result = {};
for (const match of text.matchAll(/^# (tests|suites|pass|fail|cancelled|skipped|todo|duration_ms) (\d+(?:\.\d+)?)\s*$/gm)) result[match[1]] = Number(match[2]);
assert.ok(result.tests > 0 && Number.isInteger(result.pass), 'Missing full Node TAP totals');
return result;
}
export function requireCompleteTests(totals) {
for (const name of ['fail','cancelled','skipped','todo']) assert.equal(totals[name], 0, `CI ${name} is not a verified pass`);
assert.equal(totals.pass, totals.tests, 'CI not every collected test passed');
}
+115
View File
@@ -0,0 +1,115 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { createRequire } from 'node:module';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { packageSource } from './package-source.mjs';
import { verifyOfficialContracts } from './official-contract-check.mjs';
import { createCiRun, ciEnvironment, loggedCommand, unpackVerifiedSource, verifySourceInputs, builtFiles, tapTotals, requireCompleteTests, fileDigest, writeNewJson } from './ci-utils.mjs';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const args = process.argv.slice(2), options = { profile: 'contract', outputRoot: path.join(root, '.qa/ci'), python: process.env.AGENT_WORKBENCH_TEST_PYTHON };
if (args.includes('--help')) {
console.log('node scripts/ci.mjs [--profile contract|windows] [--python ABSOLUTE_BASE_PYTHON] [--output-root DIRECTORY]\nExports committed Git source to a new directory; performs a real npm ci, official contract/build/test checks and Windows smoke. No current node_modules, data, keys or engine installation are reused. Each invocation preserves its own logs and failures.');
process.exit(0);
}
for (let i=0;i<args.length;i++) {
const name = { '--profile':'profile', '--python':'python', '--output-root':'outputRoot' }[args[i]];
if (!name || !args[i+1]) throw new Error('Unsupported CI argument; use --help');
options[name] = args[++i];
}
assert.ok(['contract','windows'].includes(options.profile));
const run = createCiRun(options.outputRoot, options.profile), env = ciEnvironment(run);
const report = { schemaVersion: 1, profile: options.profile, startedAt: new Date().toISOString(), passed: false, root: run.root, evidence: run.evidence,
commands: [], scope: { realModelRequests: 0, realKeysRead: 0, formalDataOrConfigWrites: 0, deployment: false, remoteRunClaim: false },
limitations: ['Pinned source and controlled local checks do not prove live-provider compatibility, model delivery or Purge/cache gains.', 'GitAtlas runner and remote results must be independently confirmed.', 'Formal schema2 migration and post-activation rollback remain M3 acceptance.'] };
let stage = 'preflight';
const command = async (id, executable, argv, cwd = run.source, extraEnv = {}) => {
try { const result = await loggedCommand({ id, executable, args: argv, cwd, env: { ...env, ...extraEnv }, evidence: run.evidence }); report.commands.push(result); return result; }
catch(error) { if (error.record) report.commands.push(error.record); throw error; }
};
const nodeCommand = (id, argv, cwd, extraEnv) => command(id, process.execPath, argv, cwd, extraEnv);
const readOutput = id => fs.readFileSync(path.join(run.evidence, `${id}.stdout.log`), 'utf8').trim();
try {
const git = argv => execFileSync('git', argv, { cwd: root, encoding: 'utf8', windowsHide: true, env }).trim();
const inputPaths = ['src','public','scripts','tests','.gitea','package.json','package-lock.json','vite.config.ts','tsconfig.json','index.html','mobile.html','.gitattributes'];
report.source = { commit: git(['rev-parse','HEAD']), tree: git(['rev-parse','HEAD^{tree}']), branch: git(['branch','--show-current']), worktreeStatus: git(['status','--porcelain=v1']) };
assert.equal(git(['diff','--name-only','HEAD','--',...inputPaths]), '', 'Commit program and test changes before CI; it verifies committed source only.');
assert.equal(git(['ls-files','--others','--exclude-standard','--',...inputPaths]), '', 'Untracked program or test inputs are not part of committed CI.');
const lock = JSON.parse(fs.readFileSync(path.join(root, 'scripts/ci-environment.json')));
assert.equal(lock.schemaVersion, 1); assert.equal(process.version, 'v'+lock.node, 'Use the pinned Node runtime');
if (options.profile === 'windows') assert.ok(process.platform === 'win32' && process.arch === 'x64', 'Windows profile requires actual Windows x64');
const npmCli = path.join(path.dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js');
assert.ok(fs.statSync(npmCli).isFile(), 'Use Node with its bundled npm');
await nodeCommand('npm-version', [npmCli,'--version'], run.tmp); assert.equal(readOutput('npm-version'), lock.npm, 'Pinned npm version required');
report.environment = { node: { version: process.version, executable: process.execPath, sha256: fileDigest(process.execPath) }, npm: { version: lock.npm, cli: npmCli, sha256: fileDigest(npmCli) }, platform: process.platform, arch: process.arch, ciLockSha256: fileDigest(path.join(root,'scripts/ci-environment.json')) };
if (options.profile === 'windows') {
assert.ok(options.python && path.isAbsolute(options.python) && fs.statSync(options.python).isFile(), '--python or AGENT_WORKBENCH_TEST_PYTHON must name the absolute base QA Python.');
await command('python-base', options.python, ['-I','-c','import sys,json; print(json.dumps({"version":sys.version.split()[0],"executable":sys.executable,"baseExecutable":sys._base_executable,"basePrefix":sys.base_prefix}))'], run.tmp);
const python = JSON.parse(readOutput('python-base')); assert.equal(python.version, lock.python, 'Pinned base Python version required');
report.environment.pythonBase = { ...python, sha256: fileDigest(options.python) };
}
stage = 'committed-source-export';
const archive = packageSource({ root, outputRoot: run.evidence });
writeNewJson(path.join(run.evidence,'source-archive.json'), archive);
report.source = { ...report.source, archiveSha256: archive.sha256, archiveFile: archive.path, packageLockSha256: archive.files.find(file=>file.path==='package-lock.json').sha256, files: archive.files.length };
report.sourceBefore = unpackVerifiedSource(archive, run.source);
assert.equal(fs.existsSync(path.join(run.source,'node_modules')), false, 'Fresh source must not have dependencies');
writeNewJson(path.join(run.evidence,'source-before.json'), report.sourceBefore);
stage = 'official-contracts';
await nodeCommand('official-registry', ['scripts/verify-official-model-registry.mjs',path.join(run.evidence,'official-registry-result.json')]);
await nodeCommand('official-contracts', ['scripts/verify-official-contracts.mjs','--output',path.join(run.evidence,'official-contracts-result.json')]);
const contracts = verifyOfficialContracts(run.source); report.contracts = { snapshotSha256: contracts.snapshotSha256, registryVersion: contracts.registryVersion, requestDefaultsVersion: contracts.requestDefaultsVersion, sources: contracts.sourceInventory.reduce((sum,item)=>sum+item.sources.length,0), records: contracts.recordsCount };
stage = 'fresh-npm-ci';
await nodeCommand('npm-ci', [npmCli,'ci','--no-audit','--no-fund']);
assert.equal(fs.lstatSync(path.join(run.source,'node_modules')).isSymbolicLink(), false, 'No node_modules junction reuse');
const packageLock = JSON.parse(fs.readFileSync(path.join(run.source,'package-lock.json'))), installed = {};
for (const name of ['playwright','playwright-core','electron','typescript','vite','esbuild','yaml']) {
const file = path.join(run.source,'node_modules',name,'package.json'), actual = JSON.parse(fs.readFileSync(file));
assert.equal(actual.version, packageLock.packages['node_modules/'+name].version, name+' differs from lock');
installed[name] = { version: actual.version, sha256: fileDigest(file) };
}
assert.equal(installed.playwright.version,lock.playwright); assert.equal(installed.electron.version,lock.electron);
report.environment.packages = installed;
await nodeCommand('dependency-tree', [npmCli,'ls','--all','--json']);
stage = 'workflow-contract';
await nodeCommand('workflow-check', ['scripts/verify-ci-workflow.mjs',path.join(run.evidence,'workflow.json')]);
if (options.profile === 'windows') {
stage = 'fresh-python-qa';
const venv = path.join(run.root,'python-qa');
await command('python-venv',options.python,['-I','-m','venv',venv],run.tmp);
const python = path.join(venv,'Scripts/python.exe'); env.AGENT_WORKBENCH_TEST_PYTHON = python;
await command('python-install',python,['-I','-m','pip','--isolated','install','--disable-pip-version-check','--no-input','--require-hashes','--only-binary=:all:','--index-url','https://pypi.org/simple','--cache-dir',path.join(run.cache,'pip'),'-r',path.join(run.source,'scripts/ci-python-requirements.txt')],run.tmp);
await command('python-packages',python,['-I','-c','import sys,pytest,pip,json; print(json.dumps({"python":sys.version.split()[0],"pytest":pytest.__version__,"pip":pip.__version__,"executable":sys.executable,"prefix":sys.prefix,"basePrefix":sys.base_prefix}))'],run.tmp);
const pythonInfo = JSON.parse(readOutput('python-packages')); assert.equal(pythonInfo.python,lock.python); assert.equal(pythonInfo.pytest,lock.pytest); assert.equal(pythonInfo.pip,lock.pip); assert.notEqual(pythonInfo.prefix,pythonInfo.basePrefix);
report.environment.pythonQa = { ...pythonInfo, sha256: fileDigest(python), requirementsSha256: fileDigest(path.join(run.source,'scripts/ci-python-requirements.txt')) };
await command('python-pip-check',python,['-I','-m','pip','--isolated','check'],run.tmp);
const require = createRequire(path.join(run.source,'package.json'));
const electron = require('electron'); assert.ok(fs.statSync(electron).isFile(), 'Actual Electron binary missing');
report.environment.electron = { executable: electron, sha256: fileDigest(electron) };
const { browserInstallation } = await import(pathToFileURL(path.join(run.source,'src/core/browser/browser-driver.mjs')).href);
const edge = browserInstallation(run.source); assert.equal(edge.status,'available','Actual Microsoft Edge is required; do not skip browser tests.'); report.environment.edge = edge;
stage = 'chromium-install';
await nodeCommand('chromium-install', ['node_modules/playwright/cli.js','install','chromium']);
}
stage = 'build'; await nodeCommand('build',[npmCli,'run','build']);
report.build = builtFiles(run.source); writeNewJson(path.join(run.evidence,'build-inputs.json'),report.build);
stage = 'tests';
const tests = options.profile === 'windows' ? fs.readdirSync(path.join(run.source,'tests')).filter(name=>name.endsWith('.test.mjs')).sort().map(name=>'tests/'+name) : [...contracts.testFiles,'tests/official-contracts-ci.test.mjs','tests/ci-pipeline.test.mjs','tests/source-package.test.mjs'];
const testFiles = [...new Set(tests)].sort();
writeNewJson(path.join(run.evidence,'test-inputs.json'),testFiles.map(file=>({file,sha256:fileDigest(path.join(run.source,file))})));
const testResult = await loggedCommand({id:'source-tests',executable:process.execPath,args:['--test','--test-concurrency=2','--test-reporter=tap',...testFiles],cwd:run.source,env,evidence:run.evidence,check:false}); report.commands.push(testResult);
report.tests = { files: testFiles.length, totals: tapTotals(readOutput('source-tests')), exitCode:testResult.exitCode, interrupted:testResult.interrupted };
assert.equal(testResult.exitCode,0,'Original source tests failed; preserve this run and fix the specific failure.'); assert.equal(testResult.interrupted,false); requireCompleteTests(report.tests.totals);
if (options.profile === 'windows') { stage='actual-browser-desktop-smoke'; await nodeCommand('desktop-smoke',['scripts/ci-desktop-smoke.mjs','--evidence',path.join(run.evidence,'desktop-smoke')]); report.desktopSmoke = JSON.parse(fs.readFileSync(path.join(run.evidence,'desktop-smoke/result.json'))); assert.equal(report.desktopSmoke.passed,true); }
stage='final-identity'; report.sourceAfter=verifySourceInputs(run.source,archive.files); assert.deepEqual(builtFiles(run.source),report.build,'Build artifacts changed during tests'); writeNewJson(path.join(run.evidence,'source-after.json'),report.sourceAfter);
report.passed=true;
} catch(error) {
report.failure={stage,name:error.name,message:error.message,stack:error.stack}; process.exitCode=1;
} finally {
report.finishedAt=new Date().toISOString(); writeNewJson(path.join(run.evidence,'report.json'),report);
const logFiles = fs.readdirSync(run.evidence).filter(name=>fs.statSync(path.join(run.evidence,name)).isFile()).sort();
writeNewJson(path.join(run.evidence,'MANIFEST.json'),{schemaVersion:1,files:logFiles.map(file=>({file,bytes:fs.statSync(path.join(run.evidence,file)).size,sha256:fileDigest(path.join(run.evidence,file))})),scope:'Top-level immutable command logs and reports; source/dependencies are separate owned execution inputs.'});
console.log(JSON.stringify({passed:report.passed,profile:options.profile,source:report.source?.commit,tests:report.tests,stage:report.failure?.stage,error:report.failure?.message,report:path.join(run.evidence,'report.json')}));
}
+104
View File
@@ -0,0 +1,104 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { modelRegistry, validateModelRegistry } from '../src/shared/contracts/official-model-registry.mjs';
import { REQUEST_CONTRACT_SCHEMA, REQUEST_CONTRACT_DEFAULTS_VERSION, REQUEST_CONTRACT_SOURCES, requestContractSettings } from '../src/shared/contracts/model-request-contract.mjs';
export const sha256 = value => createHash('sha256').update(value).digest('hex');
export const canonical = value => Array.isArray(value) ? value.map(canonical)
: value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
const same = (a, b) => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
const recordKey = value => JSON.stringify([value.provider, value.protocol, value.apiVersion, value.model]);
export const SOURCE_MANIFESTS = [
'tests/fixtures/official-model-registry/SOURCE.json',
'tests/fixtures/model-request-contract/SOURCE.json',
'tests/fixtures/native-cache-state/SOURCE.json',
'tests/fixtures/ci-sources/SOURCE.json',
];
export function sourceInventory(root) {
return SOURCE_MANIFESTS.map(relative => {
const file = path.join(root, relative), bytes = fs.readFileSync(file), manifest = JSON.parse(bytes);
assert.ok(Array.isArray(manifest.sources), `${relative}: missing source list`);
const names = new Set();
const sources = manifest.sources.map(source => {
assert.equal(names.has(source.id), false, `duplicate source ${source.id}`); names.add(source.id);
const sourceFile = path.resolve(path.dirname(file), source.file);
assert.ok(sourceFile.startsWith(path.join(root,'tests/fixtures') + path.sep), `source escapes pinned fixtures ${source.id}`);
assert.equal(fs.lstatSync(sourceFile).isSymbolicLink(), false, `source link ${source.id}`);
const raw = fs.readFileSync(sourceFile);
assert.equal(sha256(raw), source.sha256, `original source SHA changed: ${source.id}`);
return { id: source.id, file: source.file, url: source.url, sha256: source.sha256, bytes: raw.length, accepted: source.accepted !== false };
}).sort((a,b) => a.id.localeCompare(b.id));
return { file: relative, sha256: sha256(bytes), sources };
});
}
export function officialSnapshot(root) {
validateModelRegistry(modelRegistry);
const defaults = {};
for (const [provider, baseUrl, protocol] of [
['anthropic', 'https://api.anthropic.com', 'anthropic-messages'],
['deepseek', 'https://api.deepseek.com', 'anthropic-messages'],
['openai', 'https://api.openai.com/v1', 'responses'],
]) for (const existing of [false, true]) defaults[provider + (existing ? ':legacy' : ':new')] = requestContractSettings(undefined, { baseUrl, protocol }, { existing });
return canonical({ schemaVersion: 1,
registry: { ...structuredClone(modelRegistry), sources: [...modelRegistry.sources].sort((a,b)=>a.id.localeCompare(b.id)), records: [...modelRegistry.records].sort((a,b)=>recordKey(a).localeCompare(recordKey(b))) },
requestContract: { schemaVersion: REQUEST_CONTRACT_SCHEMA, defaultsVersion: REQUEST_CONTRACT_DEFAULTS_VERSION, sources: REQUEST_CONTRACT_SOURCES, defaults },
sourceInventory: sourceInventory(root),
});
}
export function contractDifference(before, after) {
assert.equal(before?.schemaVersion, 1, 'old contract snapshot schema'); assert.equal(after?.schemaVersion, 1, 'new contract snapshot schema');
const changes = [];
const push = (category, key, oldValue, newValue) => changes.push({ category, key, before: oldValue ?? null, after: newValue ?? null });
const beforeRecords = new Map(before.registry.records.map(item=>[recordKey(item),item]));
const afterRecords = new Map(after.registry.records.map(item=>[recordKey(item),item]));
for (const key of [...new Set([...beforeRecords.keys(), ...afterRecords.keys()])].sort()) {
const previous = beforeRecords.get(key), current = afterRecords.get(key);
if (!previous || !current) { push('model-protocol-api-version', key, previous, current); continue; }
for (const field of [...new Set([...Object.keys(previous.fields), ...Object.keys(current.fields)])].sort()) {
if (same(previous.fields[field], current.fields[field])) continue;
const category = /lifecycle|retired|alias/i.test(field) ? 'deprecation' : /cache|state/i.test(field) ? 'cache-or-state' : 'model-field';
push(category, key + '/' + field, previous.fields[field], current.fields[field]);
}
}
if (!same(before.registry.sources, after.registry.sources)) push('official-source', 'registry.sources', before.registry.sources, after.registry.sources);
if (!same(before.sourceInventory, after.sourceInventory)) push('original-source-bytes', 'sourceInventory', before.sourceInventory, after.sourceInventory);
if (!same(before.requestContract, after.requestContract)) push('request-version-auth-defaults', 'requestContract', before.requestContract, after.requestContract);
if (before.registry.version !== after.registry.version) push('registry-version', 'registry.version', before.registry.version, after.registry.version);
if (before.registry.schemaVersion !== after.registry.schemaVersion) push('registry-schema', 'registry.schemaVersion', before.registry.schemaVersion, after.registry.schemaVersion);
const registryChanged = changes.some(item=>['model-protocol-api-version','deprecation','cache-or-state','model-field','official-source','registry-schema'].includes(item.category));
return { changes, registryVersionChanged: before.registry.version !== after.registry.version,
missingRegistryVersionBump: registryChanged && before.registry.version === after.registry.version,
missingRequestVersionBump: !same(before.requestContract, after.requestContract) && before.requestContract.defaultsVersion === after.requestContract.defaultsVersion,
equal: same(before, after), reviewRequired: !same(before, after), scope: 'pinned specifications and regression inputs; no live model compatibility claim' };
}
export function verifyOfficialContracts(root) {
const indexFile = path.join(root, 'tests/fixtures/official-contracts/INDEX.json'), index = JSON.parse(fs.readFileSync(indexFile));
assert.equal(index.schemaVersion, 1); assert.ok(Array.isArray(index.history) && index.history.at(-1) === index.current);
const read = name => { assert.match(name, /^[a-zA-Z0-9_.-]+\.json$/); return JSON.parse(fs.readFileSync(path.join(path.dirname(indexFile), name))); };
const baseline = read(index.current), current = officialSnapshot(root), difference = contractDifference(baseline, current);
assert.equal(difference.equal, true, 'Official contract changed. Preserve the old snapshot, review source/version/deprecation differences and update the registry and regression baseline together.');
const suites = index.regressions;
assert.ok(Array.isArray(suites) && suites.length > 0);
const testFiles = new Set();
for (const suite of suites) {
assert.ok(typeof suite.purpose === 'string' && suite.purpose.length && Array.isArray(suite.files) && suite.files.length);
for (const file of suite.files) { assert.match(file, /^tests\/[a-z0-9-]+\.test\.mjs$/); assert.ok(fs.statSync(path.join(root, file)).isFile(), file); testFiles.add(file); }
}
const histories = index.history.map(read);
const transitions = histories.slice(1).map((value, i) => contractDifference(histories[i], value));
for (const difference of transitions) {
assert.equal(difference.missingRegistryVersionBump, false, 'Historical registry fields changed without a new version');
assert.equal(difference.missingRequestVersionBump, false, 'Historical request defaults changed without a new version');
}
return { schemaVersion: 1, passed: true, registryVersion: current.registry.version, requestDefaultsVersion: current.requestContract.defaultsVersion,
snapshotFile: index.current, snapshotSha256: sha256(fs.readFileSync(path.join(path.dirname(indexFile), index.current))),
sourceInventory: current.sourceInventory, recordsCount: current.registry.records.length, testFiles: [...testFiles].sort(), transitions,
scope: 'Fixed official bytes, model/protocol/API version facts, request defaults and named deterministic regressions. Not a live-service acceptance.' };
}
+4 -1
View File
@@ -11,6 +11,7 @@ const directories = ['src', 'public', 'scripts', 'tests', 'examples', 'benchmark
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) {
@@ -63,11 +64,13 @@ export function packageSource({ root = process.cwd(), outputRoot = path.join(roo
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, 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.' };
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.');
+36
View File
@@ -0,0 +1,36 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import YAML from 'yaml';
import { fileDigest, writeNewJson } from './ci-utils.mjs';
export function verifyCiWorkflow(root) {
const file = path.join(root,'.gitea/workflows/ci.yml'), lock = JSON.parse(fs.readFileSync(path.join(root,'scripts/ci-environment.json')));
const document = YAML.parseDocument(fs.readFileSync(file,'utf8'),{uniqueKeys:true});
assert.deepEqual(document.errors,[], 'Invalid workflow YAML'); const workflow=document.toJSON();
assert.ok(workflow.on.push && Object.hasOwn(workflow.on,'pull_request') && Object.hasOwn(workflow.on,'workflow_dispatch'));
assert.equal(Object.keys(workflow.jobs).length,1);
const job=workflow.jobs['windows-source']; assert.equal(job['runs-on'],lock.runnerLabel);
assert.equal(job['continue-on-error'],undefined); assert.equal(job['timeout-minutes'],undefined);
const uses=job.steps.filter(step=>step.uses).map(step=>step.uses);
assert.deepEqual(uses,[lock.actions.checkout,lock.actions.setupNode,lock.actions.setupPython,lock.actions.uploadArtifact]);
for(const reference of uses) assert.match(reference,/^https:\/\/(?:github\.com|gitea\.com)\/[a-z-]+\/[a-z-]+@[a-f0-9]{40}$/);
assert.equal(job.steps[0].with['persist-credentials'],false); assert.equal(job.steps[0].with['fetch-depth'],1);
assert.equal(job.steps[1].with['node-version'],lock.node); assert.equal(job.steps[2].with['python-version'],lock.python);
const execution=job.steps.find(step=>step.run); assert.equal(execution.shell,'pwsh');
assert.match(execution.run,/scripts\/ci\.mjs --profile windows --python \$qaPython --output-root \.qa\/ci/);
assert.match(execution.run,/exit \$LASTEXITCODE/);
const artifact=job.steps.at(-1); assert.equal(artifact.if,'always()'); assert.equal(artifact.with.path,'.qa/ci/**/evidence/**'); assert.equal(artifact.with['if-no-files-found'],'error');
return {passed:true,workflow:'.gitea/workflows/ci.yml',sha256:fileDigest(file),runnerLabel:lock.runnerLabel,actions:uses,
scope:'Actual YAML parse, pinned action/Node/Python refs, error propagation and evidence upload contract. Does not assert runner availability or remote execution.'};
}
if(process.argv[1] && path.resolve(process.argv[1])===fileURLToPath(import.meta.url)) {
try {
if(process.argv.length>3) throw new Error('node scripts/verify-ci-workflow.mjs [NEW_REPORT]');
const result=verifyCiWorkflow(path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'));
if(process.argv[2]) writeNewJson(path.resolve(process.argv[2]),result);
console.log(JSON.stringify(result));
} catch(error) {console.error(error.stack);process.exitCode=1;}
}
+29
View File
@@ -0,0 +1,29 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { officialSnapshot, contractDifference, verifyOfficialContracts } from './official-contract-check.mjs';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const args = process.argv.slice(2);
if (args.includes('--help')) {
console.log('node scripts/verify-official-contracts.mjs [--output NEW_FILE] | --freeze NEW_FILE | --diff OLD_FILE NEW_FILE [--output NEW_FILE]\nVerification is offline. Freeze never overwrites; preserve prior snapshots and review diffs before updating INDEX.json and regression tests. Diff-only is not a compatibility pass.');
} else {
let output, report;
try {
if (args[0] === '--freeze' && args.length === 2) {
fs.writeFileSync(path.resolve(args[1]), JSON.stringify(officialSnapshot(root), null, 2) + '\n', { flag: 'wx' });
console.log(JSON.stringify({ frozen: args[1], scope: 'snapshot only; review and regressions still required' }));
} else {
const remaining = [...args], outputIndex = remaining.indexOf('--output');
if (outputIndex !== -1) { output = remaining[outputIndex + 1]; if (!output) throw new Error('--output needs a new filename'); remaining.splice(outputIndex, 2); }
if (!remaining.length) report = verifyOfficialContracts(root);
else if (remaining[0] === '--diff' && remaining.length === 3) report = { mode: 'review-diff-only', ...contractDifference(JSON.parse(fs.readFileSync(path.resolve(remaining[1]))), JSON.parse(fs.readFileSync(path.resolve(remaining[2])))) };
else throw new Error('Unknown arguments; use --help');
if (output) fs.writeFileSync(path.resolve(output), JSON.stringify(report, null, 2) + '\n', { flag: 'wx' });
console.log(JSON.stringify({ passed: report.passed ?? null, mode: report.mode ?? 'verification', registryVersion: report.registryVersion, changes: report.changes?.length, records: report.recordsCount, testFiles: report.testFiles?.length }));
}
} catch(error) {
if (output && !fs.existsSync(path.resolve(output))) fs.writeFileSync(path.resolve(output), JSON.stringify({ passed: false, error: error.message, scope: 'offline official contract verification' }, null, 2) + '\n', { flag: 'wx' });
console.error(error.stack); process.exitCode = 1;
}
}
+64
View File
@@ -0,0 +1,64 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import YAML from 'yaml';
import { createCiRun, ciEnvironment, loggedCommand, tapTotals, requireCompleteTests, unpackVerifiedSource, fileDigest } from '../scripts/ci-utils.mjs';
import { packageSource } from '../scripts/package-source.mjs';
import { verifyCiWorkflow } from '../scripts/verify-ci-workflow.mjs';
const workspace=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
function owned(t){const root=fs.mkdtempSync(path.join(os.tmpdir(),'awb-ci-test-'));t.after(()=>{assert.equal(path.dirname(path.resolve(root)),path.resolve(os.tmpdir()));assert.ok(path.basename(root).startsWith('awb-ci-test-'));fs.rmSync(root,{recursive:true,force:true,maxRetries:5,retryDelay:100});});return root;}
test('fresh output runs are separate and excluded credential getters are never read or forwarded',t=>{
const root=owned(t),first=createCiRun(root,'contract'),second=createCiRun(root,'contract');assert.notEqual(first.root,second.root);
const input={PATH:'owned-original-path',SystemRoot:'owned-system',AGENT_WORKBENCH_TEST_PYTHON:'owned-not-approved-interpreter',ELECTRON_SKIP_BINARY_DOWNLOAD:'1'};
Object.defineProperty(input,'AGENT_WORKBENCH_API_KEY',{enumerable:true,get(){throw new Error('Credential value must never be read');}});
Object.defineProperty(input,'OPENAI_API_KEY',{enumerable:true,get(){throw new Error('Credential value must never be read');}});
const env=ciEnvironment(first,input);assert.ok(env.PATH.startsWith(path.dirname(process.execPath)));assert.equal(env.SystemRoot,'owned-system');
for(const name of ['AGENT_WORKBENCH_API_KEY','OPENAI_API_KEY','AGENT_WORKBENCH_TEST_PYTHON','ELECTRON_SKIP_BINARY_DOWNLOAD']) assert.equal(Object.hasOwn(env,name),false);
assert.equal(fs.readFileSync(env.npm_config_userconfig,'utf8'),''); assert.notEqual(env.npm_config_userconfig,env.npm_config_globalconfig);
});
test('actual nonzero command, original stdout/stderr and spawn failure survive without replay or log overwrite',async t=>{
const run=createCiRun(owned(t),'contract'),env=ciEnvironment(run);
const result=await loggedCommand({id:'original-failure',executable:process.execPath,args:['-e',"process.stdout.write('original\\n');process.stderr.write('failure\\n');process.exitCode=7"],cwd:run.source,env,evidence:run.evidence,check:false});
assert.equal(result.exitCode,7);assert.equal(fs.readFileSync(result.stdout.file,'utf8'),'original\n');assert.equal(fs.readFileSync(result.stderr.file,'utf8'),'failure\n');
const hash=fileDigest(result.stdout.file);await assert.rejects(loggedCommand({id:'original-failure',executable:process.execPath,args:['-e',"console.log('replayed')"],cwd:run.source,env,evidence:run.evidence}),/EEXIST/);assert.equal(fileDigest(result.stdout.file),hash);
const missing=await loggedCommand({id:'missing-environment',executable:path.join(run.root,'missing-python.exe'),cwd:run.source,env,evidence:run.evidence,check:false});
assert.equal(missing.spawnError.code,'ENOENT');assert.notEqual(missing.exitCode,0);assert.ok(fs.existsSync(path.join(run.evidence,'missing-environment.json')));
});
test('zero process exit with a real skipped Node test is still an incomplete CI result',async t=>{
const run=createCiRun(owned(t),'contract'),env=ciEnvironment(run),file=path.join(run.source,'skipped.test.mjs');
fs.writeFileSync(file,"import test from 'node:test';test('executed',()=>{});test.skip('missing dependency is not success',()=>{});\n");
const result=await loggedCommand({id:'skipped-tests',executable:process.execPath,args:['--test','--test-reporter=tap',file],cwd:run.source,env,evidence:run.evidence});
assert.equal(result.exitCode,0);const totals=tapTotals(fs.readFileSync(result.stdout.file,'utf8'));assert.equal(totals.skipped,1);assert.throws(()=>requireCompleteTests(totals),/skipped/);
assert.throws(()=>tapTotals('incomplete output'),/Missing full Node TAP totals/);
});
test('actual YAML, immutable action refs and original failure upload are checked instead of relying on ignored Gitea syntax',t=>{
assert.equal(verifyCiWorkflow(workspace).passed,true);
const root=owned(t);fs.mkdirSync(path.join(root,'.gitea/workflows'),{recursive:true});fs.mkdirSync(path.join(root,'scripts'));
fs.copyFileSync(path.join(workspace,'scripts/ci-environment.json'),path.join(root,'scripts/ci-environment.json'));
const document=YAML.parse(fs.readFileSync(path.join(workspace,'.gitea/workflows/ci.yml'),'utf8'));
document.jobs['windows-source'].steps.at(-1).if='success()';fs.writeFileSync(path.join(root,'.gitea/workflows/ci.yml'),YAML.stringify(document));
assert.throws(()=>verifyCiWorkflow(root));
document.jobs['windows-source'].steps.at(-1).if='always()';document.jobs['windows-source']['timeout-minutes']=30;fs.writeFileSync(path.join(root,'.gitea/workflows/ci.yml'),YAML.stringify(document));
assert.throws(()=>verifyCiWorkflow(root));
});
test('a real committed source ZIP is verified before extraction and tampering cannot replace existing input',t=>{
const root=owned(t),source=path.join(root,'source');fs.mkdirSync(source);
const git=(...args)=>execFileSync('git',args,{cwd:source,windowsHide:true,encoding:'utf8'});
git('init');fs.mkdirSync(path.join(source,'src'));fs.writeFileSync(path.join(source,'src/main.mjs'),'export const original = true;\n');
fs.writeFileSync(path.join(source,'package.json'),JSON.stringify({name:'owned',version:'1.0.0'}));fs.writeFileSync(path.join(source,'package-lock.json'),'{}\n');
git('add','--all');git('-c','user.name=CI QA','-c','user.email=ci-qa@local.invalid','commit','-m','Owned source');
const archive=packageSource({root:source,outputRoot:path.join(root,'archives')}),destination=path.join(root,'extracted');fs.mkdirSync(destination);
assert.equal(unpackVerifiedSource(archive,destination).passed,true);const original=fileDigest(path.join(destination,'src/main.mjs'));
assert.throws(()=>unpackVerifiedSource(archive,destination),/EEXIST/);assert.equal(fileDigest(path.join(destination,'src/main.mjs')),original);
fs.appendFileSync(archive.path,'tampered');const neverRun=path.join(root,'never-executed');fs.mkdirSync(neverRun);assert.throws(()=>unpackVerifiedSource(archive,neverRun),/Source ZIP SHA changed/);assert.deepEqual(fs.readdirSync(neverRun),[]);
});
+12
View File
@@ -0,0 +1,12 @@
{
"schemaVersion": 1,
"current": "registry-2026-11-07-ci1.json",
"history": ["registry-2026-11-07-ci1.json"],
"regressions": [
{"purpose": "Official registry, exact IDs, capacity facts, conflicting origins and retired aliases", "files": ["tests/official-model-registry.test.mjs", "tests/official-model-capacity.test.mjs", "tests/model-registry-integration.test.mjs", "tests/model-capacity.test.mjs"]},
{"purpose": "Messages mandatory fields, new and legacy API versions/authentication, explicit passthrough and upstream diagnostics", "files": ["tests/model-request-contract.test.mjs", "tests/model-parameter-fidelity.test.mjs", "tests/model-protocols.test.mjs", "tests/passthrough-output-diagnostics.test.mjs"]},
{"purpose": "Native cache blocks, cross-run provider state, JSON/SSE usage and original immutable request ledgers", "files": ["tests/native-cache-state.test.mjs", "tests/model-usage-accounting.test.mjs", "tests/model-stream.test.mjs", "tests/request-ledger.test.mjs"]},
{"purpose": "Model catalogue facts and routing based on current declared capability rather than branding", "files": ["tests/model-catalog.test.mjs", "tests/model-routing-capabilities.test.mjs"]}
],
"updatePolicy": "Preserve prior snapshots. Review official original bytes and version/deprecation/field differences, update the registry/defaults and behavior regressions together, add a new snapshot, append history, and make it current. Freeze alone does not prove compatibility."
}
File diff suppressed because it is too large Load Diff
+51
View File
@@ -0,0 +1,51 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { officialSnapshot, verifyOfficialContracts, contractDifference, sourceInventory, SOURCE_MANIFESTS, sha256 } from '../scripts/official-contract-check.mjs';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
test('complete pinned official sources, every registry fact and named regressions match the reviewed snapshot',()=>{
const result=verifyOfficialContracts(root); assert.equal(result.passed,true); assert.equal(result.recordsCount,26);
assert.equal(result.sourceInventory.length,4); assert.ok(result.testFiles.includes('tests/native-cache-state.test.mjs'));
for(const manifest of result.sourceInventory) for(const source of manifest.sources) assert.match(source.sha256,/^[a-f0-9]{64}$/);
});
test('an official field, retired alias, API version or original byte update cannot disappear behind an unchanged version',()=>{
const previous=officialSnapshot(root),changed=structuredClone(previous);
const alias=changed.registry.records.find(record=>record.fields.lifecycle?.value==='deprecated');
alias.fields.lifecycle.value='active';
const newVersion=structuredClone(changed.registry.records.find(record=>record.provider==='anthropic')); newVersion.apiVersion='future-official-version'; changed.registry.records.push(newVersion);
changed.registry.records[0].fields.maxOutputTokens.value+=1;
changed.sourceInventory[0].sources[0].sha256='f'.repeat(64);
const result=contractDifference(previous,changed);
assert.equal(result.equal,false); assert.equal(result.reviewRequired,true); assert.equal(result.missingRegistryVersionBump,true);
for(const category of ['deprecation','model-protocol-api-version','model-field','original-source-bytes']) assert.ok(result.changes.some(change=>change.category===category),category);
changed.registry.version+='-reviewed-next'; assert.equal(contractDifference(previous,changed).missingRegistryVersionBump,false);
assert.equal(contractDifference(previous,changed).reviewRequired,true,'A version label alone does not prove a reviewed change');
assert.equal(previous.registry.records.find(record=>record.fields.lifecycle?.value==='deprecated').fields.lifecycle.value,'deprecated');
});
test('request defaults and authentication changes require an explicit new request-contract version, independently of model facts',()=>{
const previous=officialSnapshot(root),changed=structuredClone(previous);
changed.requestContract.defaults['anthropic:new'].anthropicVersion='future-version';
let result=contractDifference(previous,changed); assert.equal(result.missingRequestVersionBump,true); assert.equal(result.missingRegistryVersionBump,false);
changed.requestContract.defaultsVersion+='-next'; result=contractDifference(previous,changed); assert.equal(result.missingRequestVersionBump,false);
assert.ok(result.changes.some(change=>change.category==='request-version-auth-defaults'));
});
test('source SHA failure remains failure even when a source was marked rejected rather than used as an official fact',t=>{
const temporary=fs.mkdtempSync(path.join(os.tmpdir(),'awb-ci-source-'));
t.after(()=>{assert.equal(path.dirname(path.resolve(temporary)),path.resolve(os.tmpdir()));assert.ok(path.basename(temporary).startsWith('awb-ci-source-'));fs.rmSync(temporary,{recursive:true,force:true});});
for(const relative of SOURCE_MANIFESTS){
const folder=path.dirname(path.join(temporary,relative));fs.mkdirSync(folder,{recursive:true});
const bytes=Buffer.from('owned-original-failure-body'); fs.writeFileSync(path.join(folder,'body.txt'),bytes);
fs.writeFileSync(path.join(temporary,relative),JSON.stringify({sources:[{id:'owned-source',file:'body.txt',sha256:sha256(bytes),accepted:false,url:'https://example.invalid/pinned'}]}));
}
assert.equal(sourceInventory(temporary)[0].sources[0].accepted,false);
fs.appendFileSync(path.join(path.dirname(path.join(temporary,SOURCE_MANIFESTS[0])),'body.txt'),'changed');
assert.throws(()=>sourceInventory(temporary),/original source SHA changed/);
});
+5 -1
View File
@@ -31,9 +31,11 @@ test('source ZIP exports committed program bytes without runtime, user data, dir
const git = args => execFileSync('git', args, { cwd: root, windowsHide: true, encoding: 'utf8' }).trim();
git(['init']);
write('package.json', JSON.stringify({ name: 'owned-source', version: '1.25.6' })); write('package-lock.json', '{}\n');
write('.gitattributes', '*.cmd text eol=crlf\n'); write('Start-Workbench.cmd', '@echo off\necho owned\n');
write('.gitattributes', '*.cmd text eol=crlf\n.gitea/workflows/*.yml text eol=lf\n'); write('Start-Workbench.cmd', '@echo off\necho owned\n');
const original = Buffer.from('\ufeff// 中文原字节\r\nexport const value = 42;\r\n'); write('src/中文.mjs', original);
for (const name of ['scripts/build.mjs', 'tests/owned.test.mjs', 'docs/PACKAGING.md', 'docs/research/NOTES.md']) write(name, 'Committed guide or code\n');
write('.gitea/workflows/ci.yml', 'name: Owned committed CI\non: [push]\n');
write('.gitea/private-setting.json', 'OWNED-EXCLUDED-CANARY');
for (const name of ['data/workbench.sqlite', '.data/session.json', '.env', 'dist-client/index.html', 'runtime/node.exe', 'docs/historical-evidence/raw.json']) write(name, 'OWNED-EXCLUDED-CANARY');
git(['add', '--all']); git(['-c', 'user.name=Source QA', '-c', 'user.email=source-qa@local.invalid', 'commit', '-m', 'Owned source fixture']);
const commit = git(['rev-parse', 'HEAD']);
@@ -49,6 +51,8 @@ test('source ZIP exports committed program bytes without runtime, user data, dir
assert.equal(row.sha256, createHash('sha256').update(archived).digest('hex'));
}
assert.ok(entries.has(prefix + 'package-lock.json')); assert.ok(entries.has(prefix + 'docs/PACKAGING.md'));
assert.equal(entries.get(prefix + '.gitea/workflows/ci.yml').toString(), 'name: Owned committed CI\non: [push]\n');
assert.equal(entries.has(prefix + '.gitea/private-setting.json'), false);
assert.equal([...entries.keys()].some(name => /(?:sqlite|session\.json|\.env|dist-client|runtime|historical-evidence|untracked)/.test(name)), false);
for (const value of entries.values()) assert.equal(value.includes('OWNED-EXCLUDED-CANARY'), false);
assert.equal(fs.readFileSync(path.join(root, 'src/中文.mjs'), 'utf8'), 'Uncommitted changed code');