docs(release): seal and deliver task agreement 1.25 with retained production state

This commit is contained in:
Agent Workbench Dev
2026-11-04 15:34:29 +08:00
parent 78976ac775
commit ddefe5f108
1444 changed files with 2161122 additions and 17 deletions
@@ -0,0 +1,5 @@
# 真实模型先导工程
Node样本为小型多币种收支汇总,三个业务模块有意不完整;固定测试、构建脚本和声明不能修改。用于真实模型/Purge提示实验成对先导观测,不是固定模型回复,也不是完整商业项目。
金额输入为有限number或去空白后符合十进制格式的string;最多两位小数,转换为安全整数分;无效/越界输入抛TypeError。分组按大写三字母币种,支持负数退款、不改原数组,输出按币种排序。报告每行“币种 金额 (笔数)”,精确两位小数。
@@ -0,0 +1,9 @@
{
"name": "owned-live-expense-report",
"private": true,
"type": "module",
"scripts": {
"test": "node --test test/expense.test.mjs",
"build": "node scripts/build.mjs"
}
}
@@ -0,0 +1,8 @@
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
for (const file of ['src/amount.mjs','src/summary.mjs','src/report.mjs']) {
const result=spawnSync(process.execPath,['--check',file],{encoding:'utf8'});
if(result.status!==0) { process.stderr.write(result.stderr);process.exit(result.status??1); }
if(!readFileSync(file,'utf8').trim()) throw new Error('Empty business module');
}
console.log('All three business modules compile.');
@@ -0,0 +1 @@
export function amountToCents(value) { return 0; }
@@ -0,0 +1 @@
export function formatReport(groups) { return ''; }
@@ -0,0 +1,2 @@
import { amountToCents } from './amount.mjs';
export function summarize(rows) { return []; }
@@ -0,0 +1,37 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { amountToCents } from '../src/amount.mjs';
import { summarize } from '../src/summary.mjs';
import { formatReport } from '../src/report.mjs';
test('decimal strings become exact cents including zero and refunds',()=>{
for(const [input,expected] of [['0',0],[' 12.34 ',1234],['+2.5',250],['-1.05',-105],['-0.00',0],['0009.10',910]]) assert.equal(amountToCents(input),expected);
});
test('finite decimal numbers use the same cents contract',()=>{
for(const [input,expected] of [[0,0],[1.01,101],[2.5,250],[-4.32,-432]]) assert.equal(amountToCents(input),expected);
});
test('malformed overprecision nonfinite and unsafe amounts are rejected',()=>{
for(const input of ['',null,undefined,true,{},'1e2','1,000','.50','1.234',1.234,NaN,Infinity,'900719925474099.99']) assert.throws(()=>amountToCents(input),TypeError,String(input));
});
test('independent currencies are sorted and summed without floating point loss',()=>{
assert.deepEqual(summarize([{currency:'usd',amount:'0.10'},{currency:' CNY ',amount:3},{currency:'USD',amount:'0.20'}]),[
{currency:'CNY',cents:300,count:1},{currency:'USD',cents:30,count:2}]);
});
test('refunds cancel totals while counting every original record',()=>{
assert.deepEqual(summarize([{currency:'eur',amount:'1.20'},{currency:'EUR',amount:'-1.20'}]),[{currency:'EUR',cents:0,count:2}]);
});
test('summarizing retains caller rows and handles an empty list',()=>{
const rows=Object.freeze([Object.freeze({currency:'usd',amount:'2.00'})]);
assert.deepEqual(summarize(rows),[{currency:'USD',cents:200,count:1}]);assert.deepEqual(summarize([]),[]);
});
test('invalid rows currency and unsafe aggregate totals are rejected',()=>{
for(const rows of [null,{},[null],[{currency:'US',amount:'1'}],[{currency:'U1D',amount:'1'}],[{currency:'USD',amount:'1.234'}],
[{currency:'USD',amount:'90071992547409.91'},{currency:'USD',amount:'0.01'}]]) assert.throws(()=>summarize(rows),TypeError);
});
test('reports use two decimals and render negative subunit amounts',()=>{
assert.equal(formatReport([{currency:'CNY',cents:300,count:2},{currency:'USD',cents:-105,count:1}]),'CNY 3.00 (2)\nUSD -1.05 (1)');
assert.equal(formatReport([{currency:'EUR',cents:-5,count:1}]),'EUR -0.05 (1)');assert.equal(formatReport([]),'');
});
test('complete expense flow preserves exact decimal sums',()=>{
assert.equal(formatReport(summarize([{currency:'usd',amount:'0.29'},{currency:'USD',amount:'-0.30'},{currency:'CNY',amount:'10.50'}])),
'CNY 10.50 (1)\nUSD -0.01 (2)');
});
@@ -0,0 +1,15 @@
# 四模块工程交付基准
[baseline/README.md](baseline/README.md)和14项测试固定初始缺失功能。`baseline`保持封存;验证器复制到独立`.qa`工程,在本地Git固定基线并增加需保留的原有工作区改动。
在已升级到1.1.0、已配置模型的工作台上,从本仓库运行:
```powershell
node scripts/verify-live-delivery.mjs
```
验证器使用工作台现有内存连接,允许模型读取当前合成工程、提出四个`src`模块改动,以及经核对的npm test/build计划。它核对提案范围、基线、保护文件hash后应用,随后调用“继续检查与交付”保留原Task。其他终端请求拒绝。
完成要求:实际失败记录、全部四文件修复、14项测试及构建通过、构建入口结果正确、保护输入与已有工作区改动保留、四源文件独立Git提交。日志、diff、会话及结果保存在`.qa/live-delivery-*/`,摘要索引为`.qa/live-delivery-validation.json`。
这是M1进入真实工程的单个受控样本。记录审核次数、模型用量与耗时,不将一次通过称为完整M2/M6能力;验收器的脚本确认、提案审查和Git提交属于已记录的人工介入替代操作。
@@ -0,0 +1,3 @@
/dist/
.awb-*
node_modules/
@@ -0,0 +1,15 @@
# Delivery Report 工程验收样本
这是有意保留缺失功能的Node工程,用于验证“失败→跨文件修复→实际测试→审查→Git交付”。本目录是封存输入,不是已完成产品。
仅修改 `src/normalize.mjs`、`src/summary.mjs`、`src/render.mjs`、`src/cli.mjs`。测试、fixtures、构建脚本、package.json与本文保持原字节。没有第三方依赖。
1. normalizeTasks接受最多10000项的数组;每项必须是对象,id/title为非空字符串且trim,trim后的id唯一。
2. status严格限定todo/doing/done/blocked;minutes必须是0到1000000之间的安全整数,拒绝文本、NaN、负数或越界;返回独立的四字段记录,不改变输入对象。
3. summarize返回total、counts(四种状态都出现)、completedPercent(done/total四舍五入到整数,空数组为0)、remainingMinutes(所有非done记录分钟数之和)。空数组计数全部为0。
4. renderText精确输出三行:`交付进度:D/T(P%)`、`待办 A · 进行中 B · 已完成 D · 阻塞 C`、`剩余预计:M 分钟`,保持中文可读。
5. CLI用法 `node src/cli.mjs <JSON文件> [--json]`。默认输出上述三行加尾换行,--json输出同一个summary的可解析JSON加换行。
6. 参数缺失、未知选项、无效JSON、无效数据或文件读取失败均以退出码2和stderr中文前缀“输入错误:”报告;stdout为空。成功退出0。
7. build核对四模块语法并复制到dist。`node dist/cli.mjs fixtures/tasks.json --json`与源码入口结果一致。
先运行npm test保存真实失败,再修改四个模块;应用提案后重跑npm test与npm run build。验收器另核对保护文件hash、源文件diff和构建入口,不把修改测试或只输出“成功”当交付。
@@ -0,0 +1,6 @@
[
{ "id": " docs ", "title": " 编写交付文档 ", "status": "done", "minutes": 30 },
{ "id": "api", "title": "接口回归", "status": "doing", "minutes": 40 },
{ "id": "release", "title": "准备发行包", "status": "blocked", "minutes": 10 },
{ "id": "review", "title": "代码审查", "status": "done", "minutes": 20 }
]
@@ -0,0 +1,7 @@
{
"name": "delivery-report-lab",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": { "test": "node --test test/*.test.mjs", "build": "node scripts/build.mjs" }
}
@@ -0,0 +1,11 @@
import fs from 'node:fs';
import { spawnSync } from 'node:child_process';
const modules = ['normalize.mjs', 'summary.mjs', 'render.mjs', 'cli.mjs'];
for (const name of modules) {
const check = spawnSync(process.execPath, ['--check', 'src/' + name], { encoding: 'utf8', windowsHide: true });
if (check.status !== 0) { process.stderr.write(check.stderr); process.exit(1); }
}
fs.mkdirSync('dist', { recursive: true });
for (const name of modules) fs.copyFileSync('src/' + name, 'dist/' + name);
fs.writeFileSync('dist/package.json', '{"type":"module"}\n');
console.log('四个模块语法检查及可运行构建完成。');
@@ -0,0 +1,8 @@
import fs from 'node:fs';
import { normalizeTasks } from './normalize.mjs';
import { summarize } from './summary.mjs';
import { renderText } from './render.mjs';
try {
const tasks = normalizeTasks(JSON.parse(fs.readFileSync(process.argv[2], 'utf8')));
console.log(renderText(summarize(tasks)));
} catch (error) { console.error(error.message); }
@@ -0,0 +1,4 @@
export function normalizeTasks(input) {
if (!Array.isArray(input)) throw new TypeError('tasks must be an array');
return input;
}
@@ -0,0 +1,3 @@
export function renderText(summary) {
return `Done: ${summary.counts.done}/${summary.total}`;
}
@@ -0,0 +1,5 @@
export function summarize(tasks) {
const done = tasks.filter(task => task.status === 'done').length;
return { total: tasks.length, counts: { done }, completedPercent: tasks.length ? 100 : 0,
remainingMinutes: tasks.reduce((sum, task) => sum + task.minutes, 0) };
}
@@ -0,0 +1,26 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { spawnSync } from 'node:child_process';
import { normalizeTasks } from '../src/normalize.mjs';
import { summarize } from '../src/summary.mjs';
import { renderText } from '../src/render.mjs';
const input = () => JSON.parse(fs.readFileSync('fixtures/tasks.json', 'utf8'));
const record = overrides => ({ id: 'one', title: '任务', status: 'todo', minutes: 5, ...overrides });
const expected = { total: 4, counts: { todo: 0, doing: 1, done: 2, blocked: 1 }, completedPercent: 50, remainingMinutes: 50 };
const invoke = (...args) => spawnSync(process.execPath, ['src/cli.mjs', ...args], { encoding: 'utf8', windowsHide: true });
test('normalize trims identifiers and titles into independent records', () => { const original = input(), before = structuredClone(original), result = normalizeTasks(original); assert.equal(result[0].id, 'docs'); assert.equal(result[0].title, '编写交付文档'); assert.notEqual(result, original); assert.notEqual(result[1], original[1]); assert.deepEqual(original, before); });
test('normalize rejects blank and duplicate normalized identifiers', () => { assert.throws(() => normalizeTasks([record({ id: ' ' })])); assert.throws(() => normalizeTasks([record({ title: ' ' })])); assert.throws(() => normalizeTasks([record(), record({ id: ' one ' })])); });
test('normalize validates record shape and bounded collection size', () => { assert.throws(() => normalizeTasks({})); assert.throws(() => normalizeTasks([null])); assert.throws(() => normalizeTasks(Array.from({ length: 10001 }, (_, i) => record({ id: String(i) })))); });
test('normalize supports all four states and rejects unknown states', () => { for (const status of ['todo', 'doing', 'done', 'blocked']) assert.equal(normalizeTasks([record({ status })])[0].status, status); assert.throws(() => normalizeTasks([record({ status: 'completed' })])); });
test('normalize rejects noninteger and out-of-range estimates', () => { for (const minutes of ['5', null, -1, 0.5, NaN, Infinity, 1000001]) assert.throws(() => normalizeTasks([record({ minutes })])); assert.equal(normalizeTasks([record({ minutes: 0 })])[0].minutes, 0); assert.equal(normalizeTasks([record({ minutes: 1000000 })])[0].minutes, 1000000); });
test('normalize emits only the declared four-field contract', () => assert.deepEqual(normalizeTasks([record({ unrelated: true })])[0], record()));
test('summary reports complete state counts and excludes completed work from remaining time', () => assert.deepEqual(summarize(normalizeTasks(input())), expected));
test('summary rounds progress instead of truncating percentages', () => assert.equal(summarize([record({ status: 'done' }), record({ id: 'two', status: 'done' }), record({ id: 'three' })]).completedPercent, 67));
test('summary handles an empty plan with every state present', () => assert.deepEqual(summarize([]), { total: 0, counts: { todo: 0, doing: 0, done: 0, blocked: 0 }, completedPercent: 0, remainingMinutes: 0 }));
test('text rendering keeps the required three readable Chinese lines', () => assert.equal(renderText(expected), '交付进度:2/4(50%)\n待办 0 · 进行中 1 · 已完成 2 · 阻塞 1\n剩余预计:50 分钟'));
test('CLI JSON output matches the summary contract and has a trailing newline', () => { const result = invoke('fixtures/tasks.json', '--json'); assert.equal(result.status, 0); assert.equal(result.stderr, ''); assert.deepEqual(JSON.parse(result.stdout), expected); assert.ok(result.stdout.endsWith('\n')); });
test('CLI text output is readable and matches the shared rendering', () => { const result = invoke('fixtures/tasks.json'); assert.equal(result.status, 0); assert.equal(result.stdout, renderText(expected) + '\n'); assert.equal(result.stderr, ''); });
test('CLI missing arguments and unknown options return exit 2 without output', () => { for (const args of [[], ['fixtures/tasks.json', '--unknown'], ['fixtures/tasks.json', '--json', '--json']]) { const result = invoke(...args); assert.equal(result.status, 2); assert.equal(result.stdout, ''); assert.match(result.stderr, /^输入错误:/); } });
test('CLI invalid JSON and missing files preserve the failure exit code', () => { for (const file of ['fixtures/invalid.json', 'fixtures/not-found.json']) { const result = invoke(file); assert.equal(result.status, 2); assert.equal(result.stdout, ''); assert.match(result.stderr, /^输入错误:/); } });
@@ -0,0 +1,7 @@
# React/TypeScript 工程交付基准 v1
baseline封存一个能构建但功能不正确的任务看板,测试与构建配置不得修改。验收修复query、summary、transition和App四文件,通过实际Node测试、TypeScript检查、Vite生产构建以及真实浏览器筛选、搜索、精确任务切换和390px布局,再由工作台生成本地Git提交与证据报告。
在产品根目录执行 `node scripts/verify-react-delivery.mjs`。验证器使用独立数据/端口与从npm缓存离线安装的固定依赖;不访问正式模型连接。API夹具提供修复代码,结果只证明工程执行和审查链路,真实模型完成率须另行验收。
验收结果在[React工程记录](../../docs/react-engine-delivery-validation.json),当前发行情况在[1.7验收](../../docs/QA-1.7.md)。
@@ -0,0 +1,4 @@
node_modules/
dist/
.env
.awb-*
@@ -0,0 +1,5 @@
# React/TypeScript 工程交付基准
此目录封存可构建但功能错误的交付看板。测试、类型声明、构建配置和用户已有修改必须保持;修复范围为query、summary、transition和App四文件。
固定React19.3.1、Vite7.3.7和TypeScript5.9.3。独立目录安装依赖后执行npm test、npm run typecheck、npm run build;真正的浏览器还需验证筛选、搜索、精确任务切换和390px布局。只通过类型/构建检查不算业务交付通过。
@@ -0,0 +1,2 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width,initial-scale=1" /><title>工程交付看板</title></head><body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>
@@ -0,0 +1,22 @@
{
"name": "react-delivery-fixture",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"test": "node --test test/*.test.mjs",
"typecheck": "tsc --noEmit",
"build": "vite build"
},
"dependencies": {
"react": "19.3.1",
"react-dom": "19.3.1"
},
"devDependencies": {
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"@vitejs/plugin-react": "5.2.0",
"typescript": "5.9.3",
"vite": "7.3.7"
}
}
@@ -0,0 +1,33 @@
import { useState } from 'react';
import { selectTasks } from './query.ts';
import { summarizeTasks } from './summary.ts';
import { toggleTask } from './transition.ts';
import type { Task } from './types.ts';
const initial: Task[] = [
{ id: 'api', title: '编写接口', done: false, hours: 3 },
{ id: 'review', title: '验证交互', done: true, hours: 2 },
{ id: 'tests', title: '完成测试', done: false, hours: 5 },
];
export default function App() {
const [tasks, setTasks] = useState(initial), [filter, setFilter] = useState('all'), [query, setQuery] = useState('');
const summary = summarizeTasks(tasks), visible = selectTasks(tasks, filter, query);
return <main className="board">
<header><p className="eyebrow">PROJECT DELIVERY</p><h1>工程交付看板</h1><p>把每一项工作推进到可交付的结果。</p></header>
<section className="summary" aria-label="项目统计">
<div><span>全部任务</span><strong>{summary.total}</strong></div>
<div><span>完成任务</span><strong>{summary.completed}</strong></div>
<div><span>待办工时</span><strong>{summary.pendingHours}<small>小时</small></strong></div>
</section>
<section className="work"><div className="controls">
<input aria-label="任务搜索" placeholder="搜索任务…" value={query} onChange={event => setQuery(event.target.value)} />
<select aria-label="任务状态" value={filter} onChange={event => setFilter(event.target.value)}>
<option value="all">全部任务</option><option value="pending">待完成</option><option value="done">已完成</option>
</select></div>
<div className="task-list">{visible.map(task => <article key={task.id} data-task={task.id}>
<div><span className={task.done ? 'tag done' : 'tag'}>{task.done ? '已完成' : '待完成'}</span><h2>{task.title}</h2><p>预计 {task.hours} 小时</p></div>
<button onClick={() => setTasks(current => toggleTask(current, 'missing'))}>{task.done ? '恢复待办' : '标为完成'}</button>
</article>)}{!visible.length && <p className="empty">没有匹配的任务</p>}</div>
</section><footer>每次改变都应能核对、能恢复。</footer>
</main>;
}
@@ -0,0 +1,4 @@
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './styles.css';
createRoot(document.getElementById('root')!).render(<App />);
@@ -0,0 +1,4 @@
import type { Task } from './types.ts';
export function selectTasks(tasks: Task[], filter: string, query: string): Task[] {
return tasks;
}
@@ -0,0 +1,26 @@
*{box-sizing:border-box}
body{margin:0;background:#f4f3ee;color:#263b35;font-family:"Segoe UI","Microsoft YaHei",sans-serif}
button,input,select{font:inherit}
button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid #267564;outline-offset:3px}
.board{max-width:1040px;margin:0 auto;padding:56px 40px}
.eyebrow{letter-spacing:.18em;font-size:11px;color:#697d72;margin-bottom:12px}
h1{font-size:32px;letter-spacing:-1px;margin:0 0 14px}
header>p:last-child{font-size:14px;color:#6c7771}
.summary{display:grid;grid-template-columns:repeat(3,1fr);gap:18px;margin:36px 0}
.summary>div{border:1px solid #dce4dc;border-radius:12px;background:#fdfefa;padding:24px}
.summary span{font-size:12px;color:#677c71}
.summary strong{display:block;font-size:32px;margin-top:10px}
.summary small{font-size:12px;font-weight:400;margin-left:8px;color:#677c71}
.work{background:#fdfefa;border:1px solid #dce4dc;border-radius:14px;padding:24px}
.controls{display:flex;gap:12px;margin-bottom:24px}
.controls input{flex:1;min-width:0}
.controls input,.controls select{padding:11px 13px;border:1px solid #dce4dc;border-radius:7px;background:#fff}
article{display:flex;justify-content:space-between;align-items:center;gap:14px;border-top:1px solid #e6ece5;padding:20px 0}
article h2{font-size:16px;margin:10px 0 8px}
article p{font-size:12px;color:#6c7771;margin:0}
article button{border:1px solid #bdd1c5;background:#eaf4ed;color:#286b55;border-radius:7px;padding:9px 12px;white-space:nowrap}
.tag{display:inline-block;font-size:10px;background:#f6efdb;color:#857545;border-radius:4px;padding:4px 6px}
.tag.done{background:#e5f1e8;color:#367351}
.empty{padding:24px 0;text-align:center;color:#77857d}
footer{font-size:12px;color:#7d8981;text-align:center;margin-top:28px}
@media(max-width:600px){.board{padding:28px 18px}h1{font-size:25px}.summary{gap:8px;margin:24px 0}.summary>div{padding:16px 10px}.summary strong{font-size:25px}.summary small{display:block;margin:4px 0 0}.work{padding:16px}.controls{gap:8px}.controls select{max-width:112px}}
@@ -0,0 +1,4 @@
import type { Task } from './types.ts';
export function summarizeTasks(tasks: Task[]) {
return { total: tasks.length, completed: 0, pendingHours: 0 };
}
@@ -0,0 +1,4 @@
import type { Task } from './types.ts';
export function toggleTask(tasks: Task[], id: string): Task[] {
return tasks.map(task => ({ ...task, done: !task.done }));
}
@@ -0,0 +1 @@
export interface Task { id: string; title: string; done: boolean; hours: number }
@@ -0,0 +1,22 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { selectTasks } from '../src/query.ts';
import { summarizeTasks } from '../src/summary.ts';
import { toggleTask } from '../src/transition.ts';
const tasks = [
{ id: 'api', title: '编写接口', done: false, hours: 3 },
{ id: 'review', title: '验证交互', done: true, hours: 2 },
{ id: 'tests', title: '完成测试', done: false, hours: 5 },
];
test('the all filter preserves all tasks', () => assert.deepEqual(selectTasks(tasks, 'all', ''), tasks));
test('pending shows only pending tasks', () => assert.deepEqual(selectTasks(tasks, 'pending', '').map(task => task.id), ['api','tests']));
test('done shows only completed tasks', () => assert.deepEqual(selectTasks(tasks, 'done', '').map(task => task.id), ['review']));
test('search combines the selected state with trimmed text', () => assert.deepEqual(selectTasks(tasks, 'done', ' 验证 ').map(task => task.id), ['review']));
test('unmatched search returns an empty list', () => assert.equal(selectTasks(tasks, 'all', '不存在').length, 0));
test('actual totals use completion states and pending hours', () => assert.deepEqual(summarizeTasks(tasks), { total: 3, completed: 1, pendingHours: 8 }));
test('toggle changes only the selected task and keeps the input intact', () => {
const original = structuredClone(tasks), changed = toggleTask(tasks, 'api');
assert.deepEqual(changed.map(task => task.done), [true,true,false]); assert.deepEqual(tasks, original);
});
test('two toggles restore the selected task', () => assert.deepEqual(toggleTask(toggleTask(tasks, 'review'), 'review'), tasks));
test('an unknown identity preserves the tasks', () => assert.deepEqual(toggleTask(tasks, 'unknown'), tasks));
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"ES2022",
"DOM",
"DOM.Iterable"
],
"module": "ESNext",
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true
},
"include": [
"src"
]
}
@@ -0,0 +1,3 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({ plugins: [react()] });
@@ -0,0 +1,9 @@
# 隔离协作的三个功能工程
这组自有样本验证实际工作区、工具、审批、原失败、修复、父归集/合并、完整检查和本地Git,固定Provider夹具提供预先定义的提案;它们不证明真实大模型的推理或自主成功率。
- Node:两个原错误模块,分别通过4项数值加法和4项完整整数区间测试;子任务只改所属模块,父工程必须8/8并构建。
- React/TypeScript:复用react-delivery-v1的9项原测试,两个独立范围各验证5/4项并类型检查/构建。父工程完整9/9,内置Edge在1280px和390px实际验证筛选、搜索、空态、单任务切换和统计。
- Python:原2项测试不变。每个子任务新增一个功能模块和4项固定测试,错误实现先实际失败,仅修复模块后各6/6;父工程金额精确转换/日程排序去重共10/10并编译。新增测试在后续修复中原字节保留。
先将AGENT_WORKBENCH_TEST_PYTHON设置为现有独立Python 3.10+解释器的绝对路径,再执行`node scripts/verify-workers-projects.mjs`。独立数据与原工件保存在本项目.qa唯一目录。每个父工程保留另行暂存、工作副本和未跟踪文件,Git只交付审查过的功能文件;运行期间输入冻结,不能修改src/scripts/tests/benchmarks或构建。
@@ -0,0 +1,12 @@
{
"name": "workers-number-library",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"test": "node --test test/*.test.mjs",
"test:add": "node --test test/add.test.mjs",
"test:range": "node --test test/range.test.mjs",
"build": "node scripts/build.mjs"
}
}
@@ -0,0 +1,9 @@
import fs from 'node:fs';
import { spawnSync } from 'node:child_process';
for (const file of ['src/add.mjs', 'src/range.mjs']) {
const checked = spawnSync(process.execPath, ['--check', file], { windowsHide: true, stdio: 'inherit' });
if (checked.status !== 0) process.exit(checked.status ?? 1);
}
fs.mkdirSync('dist', { recursive: true });
fs.cpSync('src', 'dist', { recursive: true });
console.log('Built two checked ESM library modules');
@@ -0,0 +1 @@
export function add(left, right) { return left - right; }
@@ -0,0 +1 @@
export function inclusiveRange(start, end) { return [start, end]; }
@@ -0,0 +1,9 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { add } from '../src/add.mjs';
test('positive additions return the actual sum', () => assert.equal(add(2, 3), 5));
test('negative additions preserve the signed result', () => assert.equal(add(-3, 1), -2));
test('fractional additions retain numeric precision', () => assert.ok(Math.abs(add(0.1, 0.2) - 0.3) < 1e-12));
test('nonfinite and nonnumeric inputs are rejected', () => {
for (const pair of [[Infinity, 1], ['2', 3], [NaN, 1]]) assert.throws(() => add(...pair), TypeError);
});
@@ -0,0 +1,9 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { inclusiveRange } from '../src/range.mjs';
test('inclusive ranges contain every integer between both ends', () => assert.deepEqual(inclusiveRange(1, 4), [1, 2, 3, 4]));
test('a single-point range contains exactly one number', () => assert.deepEqual(inclusiveRange(3, 3), [3]));
test('ranges cross zero without omitting negative values', () => assert.deepEqual(inclusiveRange(-2, 1), [-2, -1, 0, 1]));
test('descending fractional and oversized ranges are rejected', () => {
for (const pair of [[2, 1], [0.5, 3], [0, 10000]]) assert.throws(() => inclusiveRange(...pair), RangeError);
});
@@ -0,0 +1,17 @@
import unittest
from money import to_cents
class MoneyTests(unittest.TestCase):
def test_decimal_text_uses_exact_cents(self):
self.assertEqual(to_cents("0.29"), 29)
def test_half_cent_rounds_up(self):
self.assertEqual(to_cents("1.005"), 101)
def test_negative_half_cent_rounds_away_from_zero(self):
self.assertEqual(to_cents("-1.005"), -101)
def test_invalid_or_nonfinite_amount_is_rejected(self):
for value in ("bad", "Infinity", "NaN"):
with self.subTest(value=value), self.assertRaises(ValueError):
to_cents(value)
@@ -0,0 +1,21 @@
import unittest
from schedule import normalize_schedule
class ScheduleTests(unittest.TestCase):
def test_dates_are_sorted_chronologically(self):
self.assertEqual(normalize_schedule(["2026-11-03", "2026-10-31"]), ["2026-10-31", "2026-11-03"])
def test_duplicates_are_removed(self):
self.assertEqual(normalize_schedule(["2026-10-31", "2026-10-31"]), ["2026-10-31"])
def test_input_is_unchanged_and_empty_input_is_supported(self):
source = ["2026-11-01", "2026-10-31"]
original = list(source)
normalize_schedule(source)
self.assertEqual(source, original)
self.assertEqual(normalize_schedule([]), [])
def test_invalid_calendar_date_and_non_iso_text_are_rejected(self):
for value in ("2026-02-30", "2026/10/31", "20261031"):
with self.subTest(value=value), self.assertRaises(ValueError):
normalize_schedule([value])
@@ -0,0 +1,9 @@
[project]
name = "workers-money-schedule"
version = "0.1.0"
requires-python = ">=3.10"
[tool.agent-workbench.python]
framework = "unittest"
test-paths = ["tests"]
pattern = "test*.py"
@@ -0,0 +1,9 @@
import unittest
from util import label
class BaselineTests(unittest.TestCase):
def test_label_trims_whitespace(self):
self.assertEqual(label(" workshop "), "workshop")
def test_label_accepts_numeric_identity(self):
self.assertEqual(label(13), "13")
@@ -0,0 +1,2 @@
def label(value):
return str(value).strip()
@@ -0,0 +1,22 @@
# Delivery Report:已验证的四模块交付样本
本例由工作台内用户配置的gpt-6.1-sol完成。封存初始输入见[工程基准](../../benchmarks/node-delivery-v1/README.md):先取得13项真实测试失败,再产生四模块提案,审查应用后继续同一个Task,实际测试14/14通过并完成构建。验收文件与原工程的既有改动保留。
```powershell
npm test
npm run build
node dist/cli.mjs fixtures/tasks.json
node dist/cli.mjs fixtures/tasks.json --json
```
没有第三方依赖。Node24下默认输出:
```text
交付进度:2/4(50%)
待办 0 · 进行中 1 · 已完成 2 · 阻塞 1
剩余预计:50 分钟
```
CLI接受JSON任务数组;无效参数、JSON、数据或文件返回退出码2与中文错误。normalize/summary/render/cli分别负责输入校验、统计、中文渲染和命令行入口。14项测试覆盖输入边界、数据独立性、统计、输出、CLI参数与错误退出;build核对语法并生成dist。
这是一个受控Node样本,不能代表所有真实项目的完成率。实现来自实际配置模型;验收器负责限定脚本确认、提案审查与应用,最后保存源文件Git提交。详细结果见[真实模型验收](../../docs/m1-live-delivery-validation.json)。
@@ -0,0 +1,22 @@
import fs from 'node:fs';
import { normalizeTasks } from './normalize.mjs';
import { summarize } from './summary.mjs';
import { renderText } from './render.mjs';
try {
const args = process.argv.slice(2);
if (args.length < 1 || args.length > 2 || !args[0] || args[0].startsWith('-') ||
(args.length === 2 && args[1] !== '--json')) {
throw new TypeError('用法:node src/cli.mjs <JSON文件> [--json]');
}
const source = fs.readFileSync(args[0], 'utf8');
const tasks = normalizeTasks(JSON.parse(source));
const summary = summarize(tasks);
const output = args[1] === '--json' ? JSON.stringify(summary) : renderText(summary);
process.stdout.write(output + '\n');
process.exitCode = 0;
} catch (error) {
process.stderr.write(`输入错误:${error.message}\n`);
process.exitCode = 2;
}
@@ -0,0 +1,32 @@
const statuses = new Set(['todo', 'doing', 'done', 'blocked']);
export function normalizeTasks(input) {
if (!Array.isArray(input)) throw new TypeError('任务必须是数组');
if (input.length > 10000) throw new RangeError('任务数量不能超过10000项');
const ids = new Set();
const tasks = [];
for (const task of input) {
if (task === null || typeof task !== 'object' || Array.isArray(task)) {
throw new TypeError('每项任务必须是对象');
}
if (typeof task.id !== 'string' || typeof task.title !== 'string') {
throw new TypeError('任务id和title必须是字符串');
}
const id = task.id.trim();
const title = task.title.trim();
if (!id || !title) throw new TypeError('任务id和title不能为空');
if (ids.has(id)) throw new TypeError(`任务id重复:${id}`);
const { status, minutes } = task;
if (!statuses.has(status)) {
throw new TypeError('任务status必须是todo、doing、done或blocked');
}
if (!Number.isSafeInteger(minutes) || minutes < 0 || minutes > 1000000) {
throw new RangeError('任务minutes必须是0到1000000之间的安全整数');
}
ids.add(id);
tasks.push({ id, title, status, minutes });
}
return tasks;
}
@@ -0,0 +1 @@
{"type":"module"}
@@ -0,0 +1,8 @@
export function renderText(summary) {
const { total, counts, completedPercent, remainingMinutes } = summary;
return [
`交付进度:${counts.done}/${total}(${completedPercent}%)`,
`待办 ${counts.todo} · 进行中 ${counts.doing} · 已完成 ${counts.done} · 阻塞 ${counts.blocked}`,
`剩余预计:${remainingMinutes} 分钟`,
].join('\n');
}
@@ -0,0 +1,16 @@
export function summarize(tasks) {
const counts = { todo: 0, doing: 0, done: 0, blocked: 0 };
let remainingMinutes = 0;
for (const task of tasks) {
counts[task.status] += 1;
if (task.status !== 'done') remainingMinutes += task.minutes;
}
const total = tasks.length;
return {
total,
counts,
completedPercent: total === 0 ? 0 : Math.round(counts.done / total * 100),
remainingMinutes,
};
}
@@ -0,0 +1,6 @@
[
{ "id": " docs ", "title": " 编写交付文档 ", "status": "done", "minutes": 30 },
{ "id": "api", "title": "接口回归", "status": "doing", "minutes": 40 },
{ "id": "release", "title": "准备发行包", "status": "blocked", "minutes": 10 },
{ "id": "review", "title": "代码审查", "status": "done", "minutes": 20 }
]
@@ -0,0 +1,7 @@
{
"name": "delivery-report-lab",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": { "test": "node --test test/*.test.mjs", "build": "node scripts/build.mjs" }
}
@@ -0,0 +1,11 @@
import fs from 'node:fs';
import { spawnSync } from 'node:child_process';
const modules = ['normalize.mjs', 'summary.mjs', 'render.mjs', 'cli.mjs'];
for (const name of modules) {
const check = spawnSync(process.execPath, ['--check', 'src/' + name], { encoding: 'utf8', windowsHide: true });
if (check.status !== 0) { process.stderr.write(check.stderr); process.exit(1); }
}
fs.mkdirSync('dist', { recursive: true });
for (const name of modules) fs.copyFileSync('src/' + name, 'dist/' + name);
fs.writeFileSync('dist/package.json', '{"type":"module"}\n');
console.log('四个模块语法检查及可运行构建完成。');
@@ -0,0 +1,22 @@
import fs from 'node:fs';
import { normalizeTasks } from './normalize.mjs';
import { summarize } from './summary.mjs';
import { renderText } from './render.mjs';
try {
const args = process.argv.slice(2);
if (args.length < 1 || args.length > 2 || !args[0] || args[0].startsWith('-') ||
(args.length === 2 && args[1] !== '--json')) {
throw new TypeError('用法:node src/cli.mjs <JSON文件> [--json]');
}
const source = fs.readFileSync(args[0], 'utf8');
const tasks = normalizeTasks(JSON.parse(source));
const summary = summarize(tasks);
const output = args[1] === '--json' ? JSON.stringify(summary) : renderText(summary);
process.stdout.write(output + '\n');
process.exitCode = 0;
} catch (error) {
process.stderr.write(`输入错误:${error.message}\n`);
process.exitCode = 2;
}
@@ -0,0 +1,32 @@
const statuses = new Set(['todo', 'doing', 'done', 'blocked']);
export function normalizeTasks(input) {
if (!Array.isArray(input)) throw new TypeError('任务必须是数组');
if (input.length > 10000) throw new RangeError('任务数量不能超过10000项');
const ids = new Set();
const tasks = [];
for (const task of input) {
if (task === null || typeof task !== 'object' || Array.isArray(task)) {
throw new TypeError('每项任务必须是对象');
}
if (typeof task.id !== 'string' || typeof task.title !== 'string') {
throw new TypeError('任务id和title必须是字符串');
}
const id = task.id.trim();
const title = task.title.trim();
if (!id || !title) throw new TypeError('任务id和title不能为空');
if (ids.has(id)) throw new TypeError(`任务id重复:${id}`);
const { status, minutes } = task;
if (!statuses.has(status)) {
throw new TypeError('任务status必须是todo、doing、done或blocked');
}
if (!Number.isSafeInteger(minutes) || minutes < 0 || minutes > 1000000) {
throw new RangeError('任务minutes必须是0到1000000之间的安全整数');
}
ids.add(id);
tasks.push({ id, title, status, minutes });
}
return tasks;
}
@@ -0,0 +1,8 @@
export function renderText(summary) {
const { total, counts, completedPercent, remainingMinutes } = summary;
return [
`交付进度:${counts.done}/${total}(${completedPercent}%)`,
`待办 ${counts.todo} · 进行中 ${counts.doing} · 已完成 ${counts.done} · 阻塞 ${counts.blocked}`,
`剩余预计:${remainingMinutes} 分钟`,
].join('\n');
}
@@ -0,0 +1,16 @@
export function summarize(tasks) {
const counts = { todo: 0, doing: 0, done: 0, blocked: 0 };
let remainingMinutes = 0;
for (const task of tasks) {
counts[task.status] += 1;
if (task.status !== 'done') remainingMinutes += task.minutes;
}
const total = tasks.length;
return {
total,
counts,
completedPercent: total === 0 ? 0 : Math.round(counts.done / total * 100),
remainingMinutes,
};
}
@@ -0,0 +1,26 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { spawnSync } from 'node:child_process';
import { normalizeTasks } from '../src/normalize.mjs';
import { summarize } from '../src/summary.mjs';
import { renderText } from '../src/render.mjs';
const input = () => JSON.parse(fs.readFileSync('fixtures/tasks.json', 'utf8'));
const record = overrides => ({ id: 'one', title: '任务', status: 'todo', minutes: 5, ...overrides });
const expected = { total: 4, counts: { todo: 0, doing: 1, done: 2, blocked: 1 }, completedPercent: 50, remainingMinutes: 50 };
const invoke = (...args) => spawnSync(process.execPath, ['src/cli.mjs', ...args], { encoding: 'utf8', windowsHide: true });
test('normalize trims identifiers and titles into independent records', () => { const original = input(), before = structuredClone(original), result = normalizeTasks(original); assert.equal(result[0].id, 'docs'); assert.equal(result[0].title, '编写交付文档'); assert.notEqual(result, original); assert.notEqual(result[1], original[1]); assert.deepEqual(original, before); });
test('normalize rejects blank and duplicate normalized identifiers', () => { assert.throws(() => normalizeTasks([record({ id: ' ' })])); assert.throws(() => normalizeTasks([record({ title: ' ' })])); assert.throws(() => normalizeTasks([record(), record({ id: ' one ' })])); });
test('normalize validates record shape and bounded collection size', () => { assert.throws(() => normalizeTasks({})); assert.throws(() => normalizeTasks([null])); assert.throws(() => normalizeTasks(Array.from({ length: 10001 }, (_, i) => record({ id: String(i) })))); });
test('normalize supports all four states and rejects unknown states', () => { for (const status of ['todo', 'doing', 'done', 'blocked']) assert.equal(normalizeTasks([record({ status })])[0].status, status); assert.throws(() => normalizeTasks([record({ status: 'completed' })])); });
test('normalize rejects noninteger and out-of-range estimates', () => { for (const minutes of ['5', null, -1, 0.5, NaN, Infinity, 1000001]) assert.throws(() => normalizeTasks([record({ minutes })])); assert.equal(normalizeTasks([record({ minutes: 0 })])[0].minutes, 0); assert.equal(normalizeTasks([record({ minutes: 1000000 })])[0].minutes, 1000000); });
test('normalize emits only the declared four-field contract', () => assert.deepEqual(normalizeTasks([record({ unrelated: true })])[0], record()));
test('summary reports complete state counts and excludes completed work from remaining time', () => assert.deepEqual(summarize(normalizeTasks(input())), expected));
test('summary rounds progress instead of truncating percentages', () => assert.equal(summarize([record({ status: 'done' }), record({ id: 'two', status: 'done' }), record({ id: 'three' })]).completedPercent, 67));
test('summary handles an empty plan with every state present', () => assert.deepEqual(summarize([]), { total: 0, counts: { todo: 0, doing: 0, done: 0, blocked: 0 }, completedPercent: 0, remainingMinutes: 0 }));
test('text rendering keeps the required three readable Chinese lines', () => assert.equal(renderText(expected), '交付进度:2/4(50%)\n待办 0 · 进行中 1 · 已完成 2 · 阻塞 1\n剩余预计:50 分钟'));
test('CLI JSON output matches the summary contract and has a trailing newline', () => { const result = invoke('fixtures/tasks.json', '--json'); assert.equal(result.status, 0); assert.equal(result.stderr, ''); assert.deepEqual(JSON.parse(result.stdout), expected); assert.ok(result.stdout.endsWith('\n')); });
test('CLI text output is readable and matches the shared rendering', () => { const result = invoke('fixtures/tasks.json'); assert.equal(result.status, 0); assert.equal(result.stdout, renderText(expected) + '\n'); assert.equal(result.stderr, ''); });
test('CLI missing arguments and unknown options return exit 2 without output', () => { for (const args of [[], ['fixtures/tasks.json', '--unknown'], ['fixtures/tasks.json', '--json', '--json']]) { const result = invoke(...args); assert.equal(result.status, 2); assert.equal(result.stdout, ''); assert.match(result.stderr, /^输入错误:/); } });
test('CLI invalid JSON and missing files preserve the failure exit code', () => { for (const file of ['fixtures/invalid.json', 'fixtures/not-found.json']) { const result = invoke(file); assert.equal(result.status, 2); assert.equal(result.stdout, ''); assert.match(result.stderr, /^输入错误:/); } });
@@ -0,0 +1,9 @@
# 研究任务看板
这是 Agent Workbench 自带的小型示例项目,用来体验读取文件、提出修改、审查差异和执行验证。
## 运行
使用 `node --test` 执行测试。项目不需要安装依赖。
## 目标
把研究记录整理为可搜索的任务目录,每个条目具有标题、状态和标签。
@@ -0,0 +1 @@
{"name":"research-board-example","private":true,"type":"module","scripts":{"test":"node --test"}}
@@ -0,0 +1,15 @@
export const catalog = [
{ id: 'agent-loop', title: '工具执行循环', status: 'in_progress', tags: ['agent', 'tools'] },
{ id: 'session-recovery', title: '会话恢复', status: 'planned', tags: ['session', 'recovery'] },
{ id: 'change-review', title: '改动审查', status: 'done', tags: ['editor', 'diff'] },
];
export function searchCatalog(query) {
const normalized = query.trim().toLocaleLowerCase();
const keywords = normalized ? normalized.split(/\s+/) : [];
return catalog.filter(item => {
const searchableText = `${item.title} ${item.tags.join(' ')}`.toLocaleLowerCase();
return keywords.every(keyword => searchableText.includes(keyword));
});
}
@@ -0,0 +1,24 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { catalog, searchCatalog } from '../src/catalog.js';
test('标题与标签均可检索,忽略大小写与首尾空白', () => {
assert.deepEqual(searchCatalog('会话').map(item => item.id), ['session-recovery']);
assert.deepEqual(searchCatalog(' TOOLs ').map(item => item.id), ['agent-loop']);
});
test('多关键词搜索不受词序影响,支持跨标题与标签匹配', () => {
for (const query of ['agent tools', 'tools agent', ' TOOLs \t agent\n', 'tools 工具']) {
assert.deepEqual(searchCatalog(query).map(item => item.id), ['agent-loop']);
}
});
test('所有关键词都必须匹配同一条目', () => {
assert.deepEqual(searchCatalog('agent recovery'), []);
assert.deepEqual(searchCatalog('不存在的关键词'), []);
});
test('空查询与纯空白查询返回全部条目', () => {
assert.deepEqual(searchCatalog(''), catalog);
assert.deepEqual(searchCatalog(' \t\n '), catalog);
});
@@ -0,0 +1,5 @@
<!doctype html>
<html lang="zh-CN">
<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="theme-color" content="#154b4a" /><link rel="icon" type="image/svg+xml" href="/favicon.svg" /><title>Agent Workbench · 本地编程工作台</title></head>
<body><div id="root"></div><script type="module" src="/src/client/main.tsx"></script></body>
</html>
@@ -0,0 +1,2 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" /><meta name="theme-color" content="#172b43" /><meta name="apple-mobile-web-app-capable" content="yes" /><meta name="apple-mobile-web-app-title" content="Workbench" /><link rel="manifest" href="/mobile.webmanifest" /><link rel="icon" type="image/svg+xml" href="/mobile-icon.svg" /><link rel="apple-touch-icon" href="/mobile-touch-icon.png" /><title>Agent Workbench · 手机伴随端</title></head><body><div id="mobile-root"></div><script type="module" src="/src/client/mobile/main.tsx"></script></body></html>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,79 @@
{
"name": "local-agent-workbench",
"version": "1.25.0",
"private": true,
"type": "module",
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
"scripts": {
"dev": "vite --host 127.0.0.1",
"build": "tsc --noEmit && vite build && node scripts/build-mobile.mjs && node scripts/build-server.mjs",
"start": "node dist-server/server.mjs",
"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",
"verify:ui": "node scripts/verify-ui.mjs",
"verify:diagnostics": "node scripts/verify-diagnostics-ui.mjs",
"verify:python": "node scripts/verify-python-ui.mjs",
"verify:react": "node scripts/verify-react-delivery.mjs",
"verify:rea": "node scripts/verify-rea.mjs",
"verify:engines": "node scripts/verify-engines.mjs",
"verify:engines-ui": "node scripts/verify-engines-ui.mjs",
"verify:all-ui": "node scripts/verify-all-ui.mjs",
"package": "node scripts/package.mjs",
"verify:browser": "node scripts/verify-browser.mjs",
"verify:browser-ui": "node scripts/verify-browser-ui.mjs",
"verify:task-plans": "node scripts/verify-task-plans-ui.mjs",
"verify:model-center": "node scripts/verify-model-center-ui.mjs",
"verify:project-memory": "node scripts/verify-project-memory-ui.mjs",
"verify:task-checkpoints": "node scripts/verify-task-checkpoints-ui.mjs",
"verify:skills": "node scripts/verify-skills-ui.mjs",
"verify:mcp": "node scripts/verify-mcp-ui.mjs",
"verify:mcp-recovery": "node scripts/verify-mcp-recovery-ui.mjs",
"verify:workers": "node scripts/verify-workers-ui.mjs",
"verify:workers-projects": "node scripts/verify-workers-projects.mjs",
"verify:controlled": "node scripts/verify-controlled-ui.mjs",
"verify:controlled-projects": "node scripts/verify-controlled-projects.mjs",
"verify:purge-ui": "node scripts/verify-purge-ui.mjs",
"verify:purge-comparison": "node scripts/verify-controlled-projects.mjs --purge-comparison",
"verify:desktop-projects": "node scripts/verify-controlled-projects.mjs --desktop",
"verify:desktop-lifecycle": "node scripts/verify-controlled-ui.mjs --desktop",
"verify:desktop-install": "node scripts/verify-desktop-install.mjs",
"verify:companion": "node scripts/verify-companion-ui.mjs",
"verify:vision": "node scripts/verify-vision-ui.mjs",
"verify:vision-projects": "node scripts/verify-vision-projects.mjs",
"verify:project-cache": "node scripts/verify-project-cache-ui.mjs",
"verify:project-cache-projects": "node scripts/verify-project-cache-projects.mjs",
"verify:model-protocols": "node scripts/verify-model-protocols-ui.mjs",
"verify:evaluations": "node scripts/verify-evaluations-ui.mjs",
"verify:evaluations-projects": "node scripts/verify-evaluations-projects.mjs",
"verify:evaluations-release": "node scripts/verify-evaluations-release.mjs",
"verify:environment": "node scripts/verify-environment-ui.mjs",
"verify:embedded-browser": "node scripts/verify-embedded-browser.mjs"
},
"dependencies": {
"@babel/parser": "7.29.11",
"@peculiar/x509": "3.1.0",
"diff": "^8.0.2",
"jpeg-js": "0.4.4",
"lucide-react": "^0.548.0",
"playwright": "1.64.1",
"pngjs": "7.0.0",
"qrcode": "1.5.4",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"reflect-metadata": "0.2.2",
"smol-toml": "1.9.1",
"undici": "7.30.1"
},
"devDependencies": {
"@types/node": "^24.0.0",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react": "^5.0.4",
"electron": "45.2.0",
"esbuild": "^0.25.10",
"innosetup-compiler": "6.3.1",
"typescript": "^5.9.3",
"vite": "^7.1.12"
}
}
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect x="2" y="2" width="60" height="60" rx="14" fill="#154b4a"/><path d="M12 44l8-25h6l8 25h-6l-2-6H18l-2 6zm8-11h5l-2.5-8zm14-14h5l3 17 3-13h5l3 13 3-17h5l-5 25h-6l-2.5-13L45 44h-6z" fill="#fcfdfc"/></svg>

After

Width:  |  Height:  |  Size: 268 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 192"><rect width="192" height="192" rx="36" fill="#172b43"/><path d="M42 55h108v82H42z" fill="none" stroke="#f3f6fa" stroke-width="9"/><path d="m60 78 16 18-16 18m32 0h35" fill="none" stroke="#8bd0b9" stroke-width="9" stroke-linecap="square"/></svg>

After

Width:  |  Height:  |  Size: 307 B

@@ -0,0 +1 @@
{"id":"/","name":"Agent Workbench 手机伴随端","short_name":"Workbench","lang":"zh-CN","start_url":"/","scope":"/","display":"standalone","background_color":"#f1f4f7","theme_color":"#172b43","icons":[{"src":"/mobile-icon.svg","sizes":"any","type":"image/svg+xml","purpose":"any"},{"src":"/mobile-touch-icon.png","sizes":"256x256","type":"image/png","purpose":"any"}]}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

@@ -0,0 +1,395 @@
{
"schemaVersion": 1,
"recordedAt": "2026-10-29",
"product": "Agent Workbench",
"purpose": "Research identity and evidence-state register; planned integrations are not implemented capabilities.",
"digestRules": [
"Metadata SHA256 values were computed for the named files in this planning round.",
"Reported artifact hashes from existing Claude/Cursor reports were reused; the original artifacts were not rehashed in this round.",
"Upstream commits/archive hashes in the Desktop lock file are declarations, not proof of full local snapshot equivalence.",
"Version values identify the inspected sources; this register makes no latest-version claim."
],
"targets": [
{
"id": "codex",
"kind": "coding-agent-runtime",
"repository": "https://github.com/openai/codex",
"fixedArtifactVersion": null,
"evidenceState": "official-documentation-read; local-versioned-artifact-and-runtime-validation-pending",
"sources": [
{
"url": "https://learn.chatgpt.com/docs/app-server",
"kind": "official-documentation"
},
{
"url": "https://developers.openai.com/api/docs/guides/agents-api/architecture",
"kind": "official-documentation; hosted Agents API"
},
{
"url": "https://developers.openai.com/cookbook/examples/agents_sdk/sandboxed-code-migration/sandboxed_code_migration_agent",
"kind": "official-cookbook"
}
],
"questions": [
"CX-1",
"CX-2"
],
"capabilities": [
"C01",
"C09",
"C12",
"C14",
"C19",
"C23"
],
"runtimeValidated": false,
"integratedIntoWorkbench": false,
"gaps": [
"Pin local release/hash and generated app-server schema.",
"Validate stdio lifecycle and approval/cancellation/resume.",
"Hosted Agents API behavior is distinct from local CLI behavior.",
"WebSocket is experimental/unsupported in the inspected documentation."
]
},
{
"id": "claude-code",
"kind": "packaged-coding-agent",
"package": "@anthropic-ai/claude-code-win32-x64",
"fixedArtifactVersion": "2.1.312",
"localResearchRoot": "D:/Ai-project/REA逆向/Claude-Code-REA",
"artifact": {
"path": "D:/Ai-project/REA逆向/Claude-Code-REA/artifacts/package-extracted/package/claude.exe",
"sha256": "6099672ebe5dcb518b67d1d32dde1e3360bc6bee1dae7f8d28a69c49acc7c865",
"identityBasis": "existing report; upstream npm integrity and mapped byte evidence"
},
"evidenceState": "versioned-static-artifact-evidence",
"reports": [
"docs/research/TOOL-LOOP.md",
"docs/research/CONTEXT-RECOVERY.md"
],
"evidenceIndexes": [
"docs/research/TOOL-LOOP.evidence.json",
"docs/research/CONTEXT-RECOVERY.index.json"
],
"evidenceIds": [
"ev_78494b2b28703e1547eaa7b660ff70a6a1552991cd3b0e2727954779d74b5434"
],
"questions": [
"CC-1",
"CC-2"
],
"capabilities": [
"C02",
"C04",
"C05",
"C06",
"C07",
"C15",
"C16"
],
"runtimeValidated": false,
"integratedAsExternalEngine": false,
"gaps": [
"Static selected excerpts do not establish whole-application runtime equivalence.",
"Several helper implementations and dynamic bindings remain unknown.",
"Own implementations and their Workbench validation are tracked separately."
]
},
{
"id": "cursor",
"kind": "packaged-editor-agent",
"fixedArtifactVersion": "3.16.29",
"declaredCommit": "6246455961129c32969845e00aa25d87ae926ec0",
"localResearchRoot": "D:/Ai-project/REA逆向/investigations/cursor-agent",
"artifacts": [
{
"path": "C:/Users/wangy/AppData/Local/Programs/cursor/resources/app/extensions/cursor-agent-exec/dist/main.js",
"sha256": "ff3295964b51bc1d6446818d13660e26cca6b34ee183de6283505926b9885884",
"identityBasis": "existing versioned static report"
},
{
"path": "C:/Users/wangy/AppData/Local/Programs/cursor/resources/app/extensions/cursor-agent-worker/dist/main.js",
"sha256": "4255db956ce2f9193f65293dbd3806c60a6fd6571f7020b35cb28c1c5c513b63",
"identityBasis": "existing versioned static report"
}
],
"evidenceState": "versioned-static-artifact-evidence",
"reports": [
"docs/research/CURSOR-MECHANISMS.md"
],
"evidenceIndexes": [
"docs/research/CURSOR.evidence-index.json"
],
"evidenceIds": [
"ev_cebd28a6fee5c6940fee6249054cd080fca28e135e6083a3951c4a0a29d13b51",
"ev_789fa6618de0da72e2fde82f30aedcba8777533a0ed8c36397673fdd3792f7fe",
"ev_df7c229808fe5aa5f80a0f44fbb8c87861c3eb3593ad942d20589ada8853513d"
],
"questions": [
"CU-1",
"CU-2",
"CU-3"
],
"capabilities": [
"C02",
"C03",
"C04",
"C06",
"C07",
"C08",
"C09",
"C10",
"C16",
"C20"
],
"runtimeValidated": false,
"integratedAsExternalEngine": false,
"gaps": [
"Recorder disk ordering and crash guarantees were not validated.",
"Some final executor and worker external bindings remain unknown.",
"Packaged patch generation alone does not prove disk write success."
]
},
{
"id": "deepseek-harness",
"kind": "public-source-agent-runtime",
"repository": "https://github.com/deepseek-ai/deepseek-harness",
"localRoot": "D:/Ai-project/DeepSeek-Harness-Desktop/deepseek-harness",
"fixedSourceVersion": "0.2.1-rc.2",
"metadata": {
"path": "D:/Ai-project/DeepSeek-Harness-Desktop/deepseek-harness/package.json",
"name": "@deepseek-ai/dsh-root",
"version": "0.2.1-rc.2",
"licenseDeclaration": "MIT",
"sha256": "12bb41cd8212021a784b33a20c2b84372189a9505b42081d5e3869e21ff5cffc",
"hashScope": "package.json bytes only; not a full source-tree identity"
},
"declaredCommit": "687f282e8625c6b8d11ff58211a90524be2e4317",
"commitEvidence": "integration/sources.lock.json declaration; full snapshot equality not verified",
"evidenceState": "local-source-and-protocol-documents-read",
"sources": [
{
"path": "D:/Ai-project/DeepSeek-Harness-Desktop/deepseek-harness/apps/cli/README.md"
},
{
"path": "D:/Ai-project/DeepSeek-Harness-Desktop/deepseek-harness/packages/sdk/protocol/README.md"
},
{
"path": "D:/Ai-project/DeepSeek-Harness-Desktop/deepseek-harness/packages/sdk/client/README.md"
}
],
"profiles": [
"sdk",
"sdk-minimal"
],
"questions": [
"DS-1",
"DS-2",
"DS-3"
],
"capabilities": [
"C01",
"C02",
"C03",
"C05",
"C09",
"C10",
"C11",
"C12",
"C14",
"C15",
"C16",
"C19",
"C23"
],
"runtimeValidatedThisRound": false,
"integratedIntoWorkbench": false,
"gaps": [
"No effective protocol version negotiation.",
"No cancel/session-close methods; cancellation closes the owned runtime.",
"Server currently sends no approval request.",
"run() idle interval and finalResponse are not single-prompt causal completion.",
"Use session/wait for managed descendants and summaries.",
"Runtime-wide event ownership, profile/tool scope and persistent-session recovery require adapter validation."
]
},
{
"id": "deepseek-harness-desktop",
"kind": "separate-local-integration",
"localRoot": "D:/Ai-project/DeepSeek-Harness-Desktop",
"fixedIntegrationVersion": "0.1.1",
"metadata": {
"path": "D:/Ai-project/DeepSeek-Harness-Desktop/package.json",
"name": "deepseek-harness-local-desktop-source",
"version": "0.1.1",
"licenseDeclaration": null,
"sha256": "3bef783fac861dc85f9dd22b37818bc002b0627fc62d7204ac5595227a62473c",
"hashScope": "package.json bytes only; not a full source-tree identity"
},
"lockMetadata": {
"path": "D:/Ai-project/DeepSeek-Harness-Desktop/integration/sources.lock.json",
"sha256": "492525313e823791fc154bd0a8b8478c484c9b0821913d45095f802a752c5703"
},
"compatibilityMetadata": {
"path": "D:/Ai-project/DeepSeek-Harness-Desktop/integration/compatibility.json",
"sha256": "f7049003e3fdf3452787625e995999448a6373b6c5beb37f5c824c25b6dbd823"
},
"declaredCompatiblePair": {
"harness": "0.2.1-rc.2",
"purge": "1.1.81"
},
"developerKit": {
"metadata": {
"path": "D:/Ai-project/DeepSeek-Harness-Desktop/integration/developer-kit/package.json",
"name": "dsh-developer-kit",
"version": "0.1.0",
"licenseDeclaration": "MIT",
"sha256": "39c9bac7ffefeeaa54ffcd3df713bb0016528fc41aa945ffb114921ea70d949e",
"hashScope": "package.json bytes only; not a full source-tree identity"
},
"tools": [
"dev_project",
"dev_checks",
"dev_review"
],
"integrationStatus": "reference only; not integrated into Workbench"
},
"isAgentWorkbenchDesktop": false,
"runtimeValidatedThisRound": false,
"gaps": [
"Desktop lock/compatibility declarations require actual build/runtime and source identity checks.",
"Local integration functionality is separate from Agent Workbench product capabilities."
]
},
{
"id": "workbuddy",
"kind": "coding-and-task-client",
"fixedArtifactVersion": null,
"evidenceState": "official-documentation-read; fixed-artifact-pending",
"sources": [
{
"url": "https://www.workbuddy.cn/docs/workbuddy/Overview",
"kind": "official-documentation"
},
{
"url": "https://www.workbuddy.cn/docs/workbuddy/From-Beginner-to-Expert-Guide/Function-Description/MCP-Guide",
"kind": "official-documentation"
},
{
"path": "D:/Ai-project/REA逆向/rea/docs/client-configuration.md",
"kind": "REA client integration documentation"
},
{
"path": "D:/Ai-project/REA逆向/rea/docs/mcp-contracts.md",
"kind": "REA client contract documentation"
}
],
"questions": [
"WB-1",
"WB-2"
],
"capabilities": [
"C01",
"C05",
"C06",
"C13",
"C16",
"C20"
],
"runtimeValidated": false,
"integratedIntoWorkbench": false,
"gaps": [
"Pin user-selected or official release artifact/version/hash.",
"Documentation features are not reverse-engineered runtime proof."
]
},
{
"id": "dsh-purge-standalone",
"kind": "harness-plugin",
"repository": "https://github.com/YuJunZhiXue/dsh-purge",
"localRoot": "D:/Ai-project/REA逆向/dsh-purge-1.1.78-windows",
"fixedSourceVersion": "1.1.78",
"metadata": [
{
"path": "D:/Ai-project/REA逆向/dsh-purge-1.1.78-windows/source/upstream/package.json",
"name": "dsh-purge",
"version": "1.1.78",
"licenseDeclaration": "Apache-2.0",
"sha256": "c185af0cace16465becbb018d3bf2c2f3cfddd5133e36161b2798bddedf6cab1",
"hashScope": "package.json bytes only; not a full source-tree identity"
},
{
"path": "D:/Ai-project/REA逆向/dsh-purge-1.1.78-windows/source/local/package.json",
"name": "dsh-purge",
"version": "1.1.78",
"licenseDeclaration": "Apache-2.0",
"sha256": "c185af0cace16465becbb018d3bf2c2f3cfddd5133e36161b2798bddedf6cab1",
"hashScope": "package.json bytes only; not a full source-tree identity"
}
],
"declaredHarnessTarget": "0.2.1-rc.2",
"evidenceState": "local-source-read",
"sources": [
{
"path": "D:/Ai-project/REA逆向/dsh-purge-1.1.78-windows/source/upstream/lib/index.js"
},
{
"path": "D:/Ai-project/REA逆向/dsh-purge-1.1.78-windows/source/upstream/lib/continue-retry.js"
},
{
"path": "D:/Ai-project/REA逆向/dsh-purge-1.1.78-windows/source/upstream/LICENSE-COMMERCIAL.md"
}
],
"licenseState": "package declares Apache-2.0; additional commercial-license statement retained; distribution terms unresolved",
"questions": [
"PG-1"
],
"capabilities": [
"C18"
],
"pluginEffectValidatedThisRound": false,
"engineeringBenefitValidated": false,
"integratedIntoWorkbench": false,
"gaps": [
"Validate patch/hook activation with exact Harness/profile combination.",
"Compare real engineering outcomes with equal model/task/budget.",
"Equal package.json hashes do not prove equal complete source trees.",
"Not an OpenAI-compatible ModelProvider and not evidence of model-weight changes."
]
},
{
"id": "dsh-purge-desktop",
"kind": "harness-plugin",
"repository": "https://github.com/YuJunZhiXue/dsh-purge",
"localRoot": "D:/Ai-project/DeepSeek-Harness-Desktop/plugins/dsh-purge",
"fixedSourceVersion": "1.1.81",
"metadata": {
"path": "D:/Ai-project/DeepSeek-Harness-Desktop/plugins/dsh-purge/package.json",
"name": "dsh-purge",
"version": "1.1.81",
"licenseDeclaration": "Apache-2.0",
"sha256": "40e587aaa4d0d7210dbef8774730c9d43dc408c4e62ca553419f6c4b8770d33f",
"hashScope": "package.json bytes only; not a full source-tree identity"
},
"declaredCommit": "160b9114cbad7beca3d4d3f9f027ec843bf46f5e",
"commitEvidence": "Desktop sources.lock declaration; full snapshot equality not verified",
"declaredHarnessTarget": "0.2.1-rc.2",
"evidenceState": "local-source-and-compatibility-documents-read",
"licenseState": "package declares Apache-2.0; commercial-license statement also present; distribution terms unresolved",
"questions": [
"PG-1"
],
"capabilities": [
"C18"
],
"pluginEffectValidatedThisRound": false,
"engineeringBenefitValidated": false,
"integratedIntoWorkbench": false,
"gaps": [
"Compatibility register excludes automatic assumptions for rc.3+.",
"Do not substitute for standalone 1.1.78 without independent identity/compatibility checks.",
"Validate actual plugin effect and repeat equal-task engineering comparison."
]
}
]
}
@@ -0,0 +1,19 @@
param([string]$AppRoot = (Split-Path -Parent $PSScriptRoot), [string]$DataRoot = '', [int]$Port = 4318)
$ErrorActionPreference = 'Stop'
$AppRoot = (Resolve-Path -LiteralPath $AppRoot).Path
if (-not $DataRoot) { $DataRoot = Join-Path $env:LOCALAPPDATA 'AgentWorkbench' }
$DesktopExe = Join-Path $AppRoot 'desktop\AgentWorkbench.exe'
$NodeExe = Join-Path $AppRoot 'runtime\node.exe'
$MainFile = Join-Path $AppRoot 'dist-desktop\main.cjs'
$DesktopArgs = @('--app-root', $AppRoot, '--data-root', $DataRoot, '--port', [string]$Port)
if (-not (Test-Path -LiteralPath $DesktopExe)) {
$DesktopExe = Join-Path $AppRoot 'runtime\electron\electron.exe'
if (-not (Test-Path -LiteralPath $DesktopExe)) { $DesktopExe = Join-Path $AppRoot 'node_modules\electron\dist\electron.exe' }
if (-not (Test-Path -LiteralPath $NodeExe)) { $NodeExe = Join-Path (Split-Path -Parent $AppRoot) 'tools\node-v24.22.1-win-x64\node.exe' }
$DesktopArgs = @($MainFile) + $DesktopArgs + @('--node', $NodeExe)
}
foreach ($Required in @($DesktopExe, $NodeExe, $MainFile)) {
if (-not (Test-Path -LiteralPath $Required -PathType Leaf)) { throw "Desktop runtime file is missing: $Required" }
}
$QuotedArgs = ($DesktopArgs | ForEach-Object { if ($_ -match '"') { throw 'Invalid launch path.' }; '"' + $_ + '"' }) -join ' '
Start-Process -FilePath $DesktopExe -ArgumentList $QuotedArgs -WorkingDirectory $AppRoot -WindowStyle Hidden
@@ -0,0 +1,19 @@
[CmdletBinding()]
param([int]$Port = 0, [switch]$NoBrowser, [string]$DataRoot = '', [string]$NodePath = '')
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
$appRoot = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot))
if ($Port -eq 0) { $Port = if ($env:AGENT_WORKBENCH_PORT) { [int]$env:AGENT_WORKBENCH_PORT } else { 4318 } }
if (-not $DataRoot) { $DataRoot = if ($env:AGENT_WORKBENCH_DATA_DIR) { $env:AGENT_WORKBENCH_DATA_DIR } else { Join-Path $env:LOCALAPPDATA 'AgentWorkbench' } }
$DataRoot = [IO.Path]::GetFullPath($DataRoot)
if (-not $NodePath) { $NodePath = Join-Path $appRoot 'runtime\node.exe' }
if (-not (Test-Path -LiteralPath $NodePath)) { $NodePath = (Get-Command node.exe -ErrorAction Stop).Source }
$launcher = Join-Path $appRoot 'dist-server\host-launcher.mjs'
if (-not (Test-Path -LiteralPath $launcher)) { throw 'Build the source first, or use the complete portable package.' }
$output = & $NodePath $launcher start --app-root $appRoot --data-root $DataRoot --node $NodePath --port ([string]$Port)
if ($LASTEXITCODE -ne 0) { throw 'The host could not be verified. See the original diagnostic above.' }
$result = $output | ConvertFrom-Json
Write-Output ('Agent Workbench is ready: ' + $result.url)
Write-Output ('Data: ' + $DataRoot)
Write-Output ('Verified host PID: ' + $result.identity.pid + ' · Instance: ' + $result.identity.instanceId)
if (-not $NoBrowser) { Start-Process -FilePath $result.url }
@@ -0,0 +1,14 @@
[CmdletBinding()]
param([int]$Port = 0, [string]$DataRoot = '', [string]$NodePath = '')
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
$appRoot = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot))
if ($Port -eq 0) { $Port = if ($env:AGENT_WORKBENCH_PORT) { [int]$env:AGENT_WORKBENCH_PORT } else { 4318 } }
if (-not $DataRoot) { $DataRoot = if ($env:AGENT_WORKBENCH_DATA_DIR) { $env:AGENT_WORKBENCH_DATA_DIR } else { Join-Path $env:LOCALAPPDATA 'AgentWorkbench' } }
$DataRoot = [IO.Path]::GetFullPath($DataRoot)
if (-not $NodePath) { $NodePath = Join-Path $appRoot 'runtime\node.exe' }
if (-not (Test-Path -LiteralPath $NodePath)) { $NodePath = (Get-Command node.exe -ErrorAction Stop).Source }
$output = & $NodePath (Join-Path $appRoot 'dist-server\host-launcher.mjs') stop --app-root $appRoot --data-root $DataRoot --node $NodePath --port ([string]$Port)
if ($LASTEXITCODE -ne 0) { throw 'The original host stop remains unverified. See the diagnostic above.' }
$result = $output | ConvertFrom-Json
Write-Output ('Agent Workbench host: ' + $result.state)
@@ -0,0 +1,76 @@
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { publicSnapshot, compareOriginalState, hash } from './retained-host-state.mjs';
import { inspectHostInstallation } from '../src/core/desktop/app-installation.mjs';
// Explicit local release stages. Never sends a model request, stops an existing
// task/window, reads a private credential map, or retries an unknown installer.
const root = path.resolve('.qa/adoption-ab-release/formal'), url = 'http://127.0.0.1:4318', mode = process.argv[2];
assert.ok(['before', 'before-recheck', 'upgrade', 'final'].includes(mode)); fs.mkdirSync(root, { recursive: true });
const baseline = mode === 'before' || mode === 'before-recheck';
const read = file => JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
const save = (name, value) => fs.writeFileSync(path.join(root, name), JSON.stringify(value, null, 2) + '\n', { flag: 'wx' });
assert.equal(fs.existsSync(path.join(root, mode + '.json')), false, 'Preserve the original attempt; no automatic replay.');
async function api(route) {
const boot = await (await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' }, signal: AbortSignal.timeout(20000) })).json();
const response = await fetch(url + '/api' + route, { headers: { 'X-Workbench-Token': boot.token, Connection: 'close' }, signal: AbortSignal.timeout(20000) });
assert.equal(response.status, 200, route); return response.json();
}
async function inspectorClosed() {
await new Promise((resolve, reject) => { const socket = net.createConnection({ host: '127.0.0.1', port: 9229 }); socket.setTimeout(1500);
socket.once('connect', () => { socket.destroy(); reject(Error('Inspector is already open.')); });
socket.once('error', error => { socket.destroy(); error.code === 'ECONNREFUSED' ? resolve() : reject(error); });
socket.once('timeout', () => { socket.destroy(); reject(Error('Inspector state unknown.')); }); });
}
const startedAt = new Date().toISOString(); let result;
try {
await inspectorClosed(); const host = await api('/host/status'), dataRoot = host.identity.dataRoot;
assert.equal(host.identity.pid, 36552); assert.equal(host.activity.active, false);
// An open idle window can be recorded by a read-only baseline. Installation
// and the final retention check still require every registered window closed.
if (!baseline) assert.equal(host.desktopWindows.count, 0);
const installRoot = path.dirname(path.dirname(host.identity.runtimeRoot)); assert.equal(path.basename(path.dirname(host.identity.runtimeRoot)), 'versions');
const current = await publicSnapshot(url, dataRoot); assert.equal(current.pid, 36552); assert.equal(current.hasKey, true); assert.deepEqual(current.active, []);
if (baseline) {
assert.equal(current.version, '1.24.8'); save('state-before.json', current); save('host-before.json', host); save('pointer-before.json', read(path.join(installRoot, 'current.json')));
result = { success: true, version: current.version, pid: current.pid, dataRoot, installRoot, projects: current.projects,
sessions: current.database.sessionIds.length, desktopWindows: host.desktopWindows.count,
tables: Object.fromEntries(Object.entries(current.database.tables).map(([name, table]) => [name, table.count])) };
} else {
const before = read(path.join(root, 'state-before.json')); compareOriginalState(before, current);
const candidate = read('.qa/adoption-ab-release/candidate.json'), freeze = read('.qa/adoption-ab-release/freeze.json');
assert.equal(candidate.documentation.sourceCommit, freeze.sourceCommit);
for (const input of freeze.inputs) assert.equal(hash(fs.readFileSync(input.path)), input.sha256, 'Frozen input drift.');
for (const stage of ['rebuild', 'archives', 'portable', 'install', 'source-a', 'source-a-desktop', 'source-b', 'source-b-desktop', 'portable-a', 'portable-a-desktop', 'portable-b', 'portable-b-desktop', 'portable-files']) {
const receipt = read('.qa/adoption-ab-release/receipts/' + stage + '.json'); assert.equal(receipt.success, true, stage);
assert.equal(receipt.sourceCommit, freeze.sourceCommit); assert.equal(receipt.candidate, candidate.portableRoot); assert.equal(hash(fs.readFileSync(receipt.log)), receipt.logSha256);
}
if (mode === 'upgrade') {
assert.equal(current.version, before.version); assert.deepEqual(read(path.join(installRoot, 'current.json')), read(path.join(root, 'pointer-before.json')));
assert.equal(hash(fs.readFileSync(candidate.installer.path)), candidate.installer.sha256);
save('candidate.json', candidate); save('preinstall-state.json', current);
const fd = fs.openSync(path.join(root, 'installer-process.log'), 'wx'); let code;
try { code = await new Promise((resolve, reject) => {
const child = spawn(candidate.installer.path, ['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/LOG=' + path.join(root, 'installer.log'), '/DIR=' + installRoot, '/DATA_ROOT=' + dataRoot, '/PORT=4318'], { windowsHide: true, stdio: ['ignore', fd, fd] });
child.once('error', reject); child.once('close', resolve);
}); } finally { fs.closeSync(fd); }
save('installer-exit.json', { code, finishedAt: new Date().toISOString() }); assert.equal(code, 0, 'Do not replay a failed/unknown formal installation.');
} else { assert.equal(read(path.join(root, 'upgrade.json')).success, true); assert.deepEqual(candidate, read(path.join(root, 'candidate.json'))); }
const after = await publicSnapshot(url, dataRoot), retention = compareOriginalState(before, after), afterHost = await api('/host/status');
assert.equal(after.version, '1.24.9'); assert.equal(after.pid, before.pid);
assert.equal(afterHost.identity.instanceId, read(path.join(root, 'host-before.json')).identity.instanceId);
const installed = path.join(installRoot, 'versions', path.basename(candidate.portableRoot)); assert.equal(fs.realpathSync.native(after.runtimeRoot), fs.realpathSync.native(installed));
const identity = inspectHostInstallation(installed), pointer = read(path.join(installRoot, 'current.json'));
assert.equal(pointer.active.directory, path.basename(installed)); assert.equal(pointer.active.manifestSha256, identity.manifestSha256); assert.equal(pointer.active.runtimeIdentity, identity.identitySha256);
const operation = fs.readdirSync(path.join(installRoot, '.installation')).filter(name => /^progress-.*\.json$/.test(name)).map(name => read(path.join(installRoot, '.installation', name))).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0];
assert.equal(operation.state, 'completed'); assert.equal(operation.candidate.manifestSha256, identity.manifestSha256); await inspectorClosed();
save(mode + '-state-after.json', after); result = { success: true, version: after.version, pid: after.pid, runtimeRoot: after.runtimeRoot,
projects: after.projects, sessions: after.database.sessionIds.length, hasKey: after.hasKey, retention, sourceCommit: freeze.sourceCommit,
pointer, operation, inspectorClosed: true, desktopWindows: afterHost.desktopWindows.count };
}
} catch (error) { result = { success: false, error: error.stack }; process.exitCode = 1; }
result = { ...result, mode, startedAt, finishedAt: new Date().toISOString(), realModelRequests: 0, keyReadOrResaved: false };
save(mode + '.json', result); console.log(JSON.stringify({ success: result.success, mode, version: result.version, pid: result.pid, error: result.error }));
@@ -0,0 +1,77 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { execFileSync, spawn } from 'node:child_process';
import { projectEnvironment } from '../src/core/process-environment.mjs';
const root = path.resolve('.qa/adoption-ab-release'), mode = process.argv[2];
const read = file => JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
const save = (name, value) => { const file = path.join(root, name); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' }); };
const hash = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
const record = file => ({ path: file.replaceAll('\\', '/'), bytes: fs.statSync(file).size, sha256: hash(file) });
const walk = directory => fs.readdirSync(directory, { withFileTypes: true }).flatMap(row => row.isDirectory() ? walk(path.join(directory, row.name)) : [path.join(directory, row.name)]);
const python = 'C:/Users/wangy/AppData/Local/Programs/Python/Python312/python.exe';
fs.mkdirSync(root, { recursive: true });
if (mode === 'freeze') {
assert.equal(execFileSync('git', ['status', '--porcelain'], { encoding: 'utf8', windowsHide: true }).trim(), '');
assert.equal(read('package.json').version, '1.24.9');
const inputs = execFileSync('git', ['ls-files', '-z', '--', 'src', 'public', 'scripts', 'tests', 'examples', 'benchmarks', 'research', 'package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'index.html', 'mobile.html'], { encoding: 'utf8', windowsHide: true }).split('\0').filter(Boolean).sort();
const freeze = { sourceCommit: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8', windowsHide: true }).trim(), version: '1.24.9',
inputs: inputs.map(record), compiled: ['dist-client', 'dist-server', 'dist-desktop'].flatMap(walk).sort().map(record), realModelRequests: 0 };
save('freeze.json', freeze); console.log(JSON.stringify({ success: true, sourceCommit: freeze.sourceCommit, inputs: freeze.inputs.length, compiled: freeze.compiled.length })); process.exit(0);
}
const freeze = read(path.join(root, 'freeze.json'));
for (const row of freeze.inputs) assert.equal(hash(row.path), row.sha256, 'Frozen input drift: ' + row.path);
if (mode === 'register') {
const candidate = read('releases/latest.json'); assert.equal(candidate.documentation.sourceCommit, freeze.sourceCommit);
assert.equal(read(path.join(candidate.portableRoot, 'MANIFEST.json')).version, freeze.version);
for (const row of freeze.compiled) assert.equal(hash(path.join(candidate.portableRoot, row.path)), row.sha256);
save('candidate.json', candidate); console.log(JSON.stringify({ success: true, candidate: candidate.portableRoot })); process.exit(0);
}
const candidate = read(path.join(root, 'candidate.json')); assert.deepEqual(read('releases/latest.json'), candidate);
const commands = {
rebuild: [process.execPath, ['scripts/verify-packaged-build.mjs']],
archives: [python, ['-I', 'scripts/verify-archives.py']],
portable: [process.execPath, ['scripts/verify-release.mjs']],
install: [process.execPath, ['scripts/verify-desktop-install.mjs']],
'source-a': [process.execPath, ['scripts/verify-requirements-ui.mjs']],
'source-a-desktop': [process.execPath, ['scripts/verify-requirements-desktop.mjs']],
'source-b': [process.execPath, ['scripts/verify-turn-progress-ui.mjs']],
'source-b-desktop': [process.execPath, ['scripts/verify-turn-progress-ui.mjs', '--desktop']],
'portable-a': [process.execPath, ['scripts/verify-requirements-ui.mjs']],
'portable-a-desktop': [process.execPath, ['scripts/verify-requirements-desktop.mjs']],
'portable-b': [process.execPath, ['scripts/verify-turn-progress-ui.mjs']],
'portable-b-desktop': [process.execPath, ['scripts/verify-turn-progress-ui.mjs', '--desktop']],
'portable-files': [process.execPath, ['scripts/verify-local-files.mjs']],
};
assert.ok(commands[mode], 'Unknown release stage.');
const output = path.join(root, 'receipts', mode + '.json'), log = path.join(root, 'logs', mode + '.log');
assert.equal(fs.existsSync(output), false, 'Preserve previous stage receipt; do not replay unknown work.'); fs.mkdirSync(path.dirname(log), { recursive: true });
const fd = fs.openSync(log, 'wx'), startedAt = new Date().toISOString();
const env = projectEnvironment({ AGENT_WORKBENCH_TEST_PYTHON: python,
...((mode.startsWith('portable-') || mode === 'install') ? { AGENT_WORKBENCH_QA_APP_ROOT: candidate.portableRoot } : {}) });
let result, code;
try {
console.log('START ' + mode);
code = await new Promise((resolve, reject) => { const child = spawn(...commands[mode], { env, windowsHide: true, stdio: ['ignore', fd, fd] }); child.once('error', reject); child.once('close', resolve); });
fs.closeSync(fd); assert.equal(code, 0, 'Inspect preserved log: ' + log);
assert.deepEqual(read('releases/latest.json'), candidate);
let file;
if (mode === 'archives') file = '.qa/archives-validation.json';
else if (mode === 'portable') file = '.qa/release-validation.json';
else if (mode === 'install') file = read('.qa/desktop-install-location.json').result;
else {
const summaries = fs.readFileSync(log, 'utf8').trim().split(/\r?\n/).filter(line => line.startsWith('{')).map(line => { try { return JSON.parse(line); } catch { return null; } });
const summary = summaries.findLast(row => row?.success !== undefined); assert.ok(summary);
file = summary.output ?? path.join(summary.directory ?? summary.root, 'result.json');
}
const value = read(file); assert.equal(value.success, true);
if (mode !== 'archives') assert.equal(value.version, freeze.version);
if (mode.startsWith('portable-')) assert.equal(fs.realpathSync.native(value.appRoot), fs.realpathSync.native(candidate.portableRoot));
if (mode === 'install') assert.equal(fs.realpathSync.native(value.packagedSource), fs.realpathSync.native(candidate.portableRoot));
if (mode === 'rebuild') assert.equal(value.sourceCommit, freeze.sourceCommit);
result = { success: true, resultPath: path.resolve(file), result: value };
} catch (error) { result = { success: false, code, error: error.stack }; process.exitCode = 1; }
result = { ...result, mode, log, logSha256: hash(log), startedAt, finishedAt: new Date().toISOString(), sourceCommit: freeze.sourceCommit, candidate: candidate.portableRoot, realModelRequests: 0 };
save('receipts/' + mode + '.json', result); console.log(JSON.stringify({ success: result.success, mode, output, resultPath: result.resultPath, error: result.error }));
@@ -0,0 +1,71 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
const root = path.resolve('docs/live-original-purge-h-evidence');
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
const read = relative => JSON.parse(fs.readFileSync(path.join(root, relative)));
const manifest = read('manifest.json');
for (const entry of manifest.entries) {
const raw = fs.readFileSync(path.join(root, entry.path)); assert.equal(raw.length, entry.bytes); assert.equal(sha(raw), entry.sha256);
}
const core = {};
for (const row of read('receipts/owned-records.json')) (core[row.kind] ??= new Map()).set(row.id, JSON.parse(row.payload));
const artifacts = new Map(manifest.artifacts.map(a => [a.id, a]));
function artifact(id) { const a = artifacts.get(id); assert.ok(a, id); return JSON.parse(fs.readFileSync(path.join(root, a.file))); }
const attempts = read('receipts/all-model-attempts.json');
function strings(value, output = [], depth = 0) {
if (depth > 12) return output;
if (typeof value === 'string') {
output.push(value);
for (const text of new Set([value, ...value.split('\n').filter(line => /^\s*[\[{]/.test(line))])) {
if (/^\s*[\[{]/.test(text)) { try { strings(JSON.parse(text), output, depth + 1); } catch {} }
}
} else if (value && typeof value === 'object') for (const v of Object.values(value)) strings(v, output, depth + 1);
return output;
}
function covered(ranges,start,end){if(end<=start)return false;let cursor=start;for(const r of ranges.slice().sort((a,b)=>a.start-b.start)){if(r.end<=cursor)continue;if(r.start>cursor)return false;cursor=Math.max(cursor,r.end);if(cursor>=end)return true;}return false;}
assert.equal(covered([{start:0,end:4},{start:4,end:8}],2,6),true);
assert.equal(covered([{start:0,end:2},{start:4,end:8}],1,5),false);
assert.equal(covered([{start:0,end:8}],3,3),false);
const reports = [];
for (const sample of manifest.samples.slice(0, 2)) {
const exported=read('owned-exports/'+sample.sessionId+'.json');
const applied=exported.session.changes.filter(c=>c.status==='applied'&&c.appliedAt);
const currentSource=(r,at)=>{const c=applied.filter(c=>c.path===r.path&&c.appliedAt<at).sort((a,b)=>a.appliedAt.localeCompare(b.appliedAt)).at(-1);return !c||c.sha256===r.sourceSha256;};
const tools = [...core.tool.values()].filter(t => t.sessionId === sample.sessionId)
.map(t => ({ ...t, result: t.result ?? (t.resultArtifactId ? artifact(t.resultArtifactId) : null) }))
.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
const reads = tools.filter(t => t.tool === 'read_file' && t.result?.content).map(t => ({ path: t.result.path, start: t.result.start_line, end: t.result.end_line,
complete: !t.result.truncated && t.result.start_line === 1 && t.result.end_line === t.result.total_lines,
content: t.result.content, sourceSha256:t.result.sha256, toolId: t.id, at: t.finishedAt }));
const ranges = new Map();
const pages = tools.filter(t => t.tool === 'read_artifact').map(t => {
const r = t.result, id = r?.artifact_id, a = artifacts.get(id);
if (!id) return { toolId: t.id, state: t.state, resultKeys: Object.keys(r ?? {}) };
const prior = ranges.get(id) ?? [], start = r.offset, end = r.next_offset;
const alreadyCovered = covered(prior,start,end);
const overlap = prior.some(p => p.start < end && start < p.end);
prior.push({ start, end }); ranges.set(id, prior);
let source;
try { const value = JSON.parse(r.content); source = { path: value.path, tool: value.tool, keys: Object.keys(value).slice(0, 10) }; } catch {}
return { toolId: t.id, at: t.finishedAt, artifactId: id, kind: a?.kind, sha256: a?.sha256, offset: start, nextOffset: end,
total: r.total_characters, truncated: r.truncated, alreadyCovered, overlap, source };
});
const requestReports = attempts.filter(a => a.sessionId === sample.sessionId).sort((a, b) => a.startedAt.localeCompare(b.startedAt)).map((a, i) => {
const request = artifact(a.requestArtifactId), bodyStrings = strings(request.messages ?? request.input ?? request);
const before = reads.filter(r => r.at < a.startedAt);
return { request: i + 1, attemptId: a.id, reportedTokens: a.usage?.total_tokens, startedAt: a.startedAt,
completeSource: before.filter(r => r.complete).map(r => ({ path: r.path, toolId: r.toolId, sourceSha256:r.sourceSha256, currentAtDispatch:currentSource(r,a.startedAt), retained: bodyStrings.some(s => s.includes(r.content)) })),
toolsBefore: tools.filter(t => t.finishedAt < a.startedAt).length };
});
const prepared = tools.findIndex(t => t.tool === 'prepare_change_set' && t.state === 'completed');
reports.push({ name: sample.name, sessionId: sample.sessionId, tools: tools.map(t => ({ toolId: t.id, name: t.tool, state: t.state, at: t.finishedAt,
resultKeys: Object.keys(t.result ?? {}), ...(t.tool === 'prepare_change_set' ? { result: t.result } : {}) })),
reads: reads.map(({ content, ...r }) => ({ ...r, characters: content.length })), pages, requests: requestReports,
afterPrepared: prepared < 0 ? [] : tools.slice(prepared + 1).map(t => ({ name: t.tool, at: t.finishedAt, state: t.state })) });
}
const result = { success: true, manifestSha256: sha(fs.readFileSync(path.join(root, 'manifest.json'))), realModelRequests: 0, auditVersion:2, originalAuditSha256:sha(fs.readFileSync('docs/live-retest-h-efficiency-audit.json')), corrections:['Repeated artifact page coverage uses the union of all prior returned character ranges.','Source reads invalidated by an applied change are explicitly marked stale; their absence is not a lost-current-source finding.'],
scope: 'Offline observations of sealed new H samples only. Exact source retention checks inspect nested JSON tool content; repeated artifact pages are measured by original byte-identity and returned character interval. No source changes or inferred model cognition.', reports };
fs.writeFileSync('docs/live-retest-h-efficiency-audit-v2.json', JSON.stringify(result, null, 2) + '\n', { flag: 'wx' });
for(const r of reports)console.log(JSON.stringify({name:r.name,toolCalls:r.tools.length,completeReads:r.reads.filter(x=>x.complete).length,repeatedPages:r.pages.filter(p=>p.alreadyCovered&&p.nextOffset>p.offset).length,requests:r.requests.map(q=>({request:q.request,completeRead:q.completeSource.length,currentSource:q.completeSource.filter(f=>f.currentAtDispatch).length,currentRetained:q.completeSource.filter(f=>f.currentAtDispatch&&f.retained).length})),afterPrepared:r.afterPrepared}));
@@ -0,0 +1,44 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { validateInstalledVersion } from '../src/core/desktop/install-manager.mjs';
export function buildWindowsInstaller({ root, portableRoot, outputRoot, name = null, qaFixture = null }) {
const packageRoot = path.join(root, 'node_modules/innosetup-compiler'), compiler = path.join(packageRoot, 'bin/ISCC.exe');
const meta = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
if (meta.version !== '6.3.1' || !fs.existsSync(compiler)) throw new Error('The pinned, script-free Inno Setup compiler 6.3.1 is required.');
const manifest = JSON.parse(fs.readFileSync(path.join(portableRoot, 'MANIFEST.json'), 'utf8'));
if (manifest.app !== 'agent-workbench' || manifest.kind !== 'portable') throw new Error('Installer requires a full portable candidate.');
validateInstalledVersion(portableRoot);
for (const value of [root, portableRoot, outputRoot]) if (!path.isAbsolute(value) || /["\r\n]/.test(value)) throw new Error('Installer build requires absolute local paths.');
const directory = path.join(root, '.qa', 'installer-build-' + randomUUID()); fs.mkdirSync(directory, { recursive: true });
fs.mkdirSync(outputRoot, { recursive: true });
const outputName = name ?? path.basename(portableRoot) + '-Setup';
if (!/^[A-Za-z0-9._-]+$/.test(outputName) || fs.existsSync(path.join(outputRoot, outputName + '.exe'))) throw new Error('Installer output must be a new simple name.');
let template = fs.readFileSync(path.join(root, 'src/desktop/installer.iss'), 'utf8');
if (qaFixture) {
if (!/^[a-f0-9-]{36}$/.test(qaFixture.appId ?? '') || !['none', 'corrupt-installed-candidate'].includes(qaFixture.fault ?? 'none')) throw new Error('Invalid isolated installer QA fixture.');
template = template.replace('E914E883-46F9-4B82-B27F-BDB2B40DCC90', qaFixture.appId)
.replace('DefaultGroupName=Agent Workbench', 'DefaultGroupName=Agent Workbench QA ' + qaFixture.appId);
if (qaFixture.fault === 'corrupt-installed-candidate') template = template.replace("if CurStep = ssPostInstall then begin", "if CurStep = ssPostInstall then begin\n { Explicit owned QA fault, never included by the product packaging CLI. }\n if not SaveStringToFile(ExpandConstant('{app}\\versions\\{#VersionDirectory}\\dist-client\\index.html'), 'owned-candidate-corruption', True) then RaiseException('QA fault injection failed');");
}
const literal = value => String(value).replaceAll('"', '""');
const manifestSha256 = createHash('sha256').update(fs.readFileSync(path.join(portableRoot, 'MANIFEST.json'))).digest('hex');
const prefix = [['PortableRoot', portableRoot], ['OutputRoot', outputRoot], ['OutputName', outputName], ['Version', manifest.version], ['VersionDirectory', path.basename(portableRoot)], ['ManifestSha256', manifestSha256]]
.map(([key, value]) => '#define ' + key + ' "' + literal(value) + '"').join('\n') + '\n';
const source = path.join(directory, 'installer.iss'); fs.writeFileSync(source, '\uFEFF' + prefix + template, 'utf8');
let output;
try { output = execFileSync(compiler, ['/Q', source], { cwd: directory, windowsHide: true, encoding: 'utf8', timeout: 600000, maxBuffer: 4 * 1024 * 1024 }); }
catch (error) { const bytes = value => Buffer.isBuffer(value) ? value : Buffer.from(value ?? ''); fs.writeFileSync(path.join(directory, 'compile-failure.txt'), Buffer.concat([bytes(error.stdout), bytes(error.stderr)])); throw error; }
fs.writeFileSync(path.join(directory, 'compile.txt'), output);
const file = path.join(outputRoot, outputName + '.exe');
return { path: file, bytes: fs.statSync(file).size, sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex'), compiler: { version: meta.version, sha256: createHash('sha256').update(fs.readFileSync(compiler)).digest('hex') }, source, version: manifest.version, candidateDirectory: path.basename(portableRoot), qaFixture };
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const args = process.argv.slice(2), values = {};
if (args.length === 1 && args[0] === '--help') { console.log('node scripts/build-installer.mjs --portable-root DIRECTORY [--output-root DIRECTORY] — compile the pinned user-level installer from an immutable manifest.'); process.exit(0); }
while (args.length) { const key = args.shift(); if (!['--portable-root', '--output-root'].includes(key) || values[key] || !args.length) throw new Error('Use --help.'); values[key] = args.shift(); }
console.log(JSON.stringify(buildWindowsInstaller({ root: process.cwd(), portableRoot: values['--portable-root'], outputRoot: values['--output-root'] ?? path.resolve('releases') })));
}
@@ -0,0 +1,42 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
// Vite's dependency graph defines the complete mobile allowlist. Desktop
// entries, arbitrary files and future chunks are not implicitly exposed.
const root = path.resolve('dist-client'), manifest = JSON.parse(fs.readFileSync(path.join(root, '.vite/manifest.json'), 'utf8'));
const seen = new Set(), assets = new Set();
function visit(name) {
if (seen.has(name)) return; seen.add(name);
const entry = manifest[name]; if (!entry) throw new Error('Mobile build dependency is missing: ' + name);
for (const file of [entry.file, ...(entry.css ?? []), ...(entry.assets ?? [])]) {
if (!/^assets\/[A-Za-z0-9_.-]+\.(js|css)$/.test(file)) throw new Error('Unexpected mobile asset: ' + file);
if (!fs.statSync(path.join(root, file)).isFile()) throw new Error('Mobile asset is not a file: ' + file);
assets.add('/' + file);
}
for (const imported of [...(entry.imports ?? []), ...(entry.dynamicImports ?? [])]) visit(imported);
}
visit('mobile.html');
const list = [...assets].sort();
fs.writeFileSync(path.join(root, 'mobile-assets.json'), JSON.stringify(list, null, 2) + '\n');
// Reuse our existing raster mark for iPhone's home-screen icon; no generated
// media or network dependency is needed for this product asset.
const icon = fs.readFileSync(path.join(root, 'workbench-icon.png'));
fs.writeFileSync(path.join(root, 'mobile-touch-icon.png'), icon);
const version = createHash('sha256').update(fs.readFileSync(path.join(root, 'mobile.html'))).update(JSON.stringify(list)).digest('hex').slice(0, 20);
const files = ['/', '/mobile.webmanifest', '/mobile-icon.svg', '/mobile-touch-icon.png', ...list];
const worker = `const CACHE = 'workbench-mobile-${version}';
const FILES = ${JSON.stringify(files)};
self.addEventListener('install', event => event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(FILES)).then(() => self.skipWaiting())));
self.addEventListener('activate', event => event.waitUntil(caches.keys().then(names => Promise.all(names.filter(name => name.startsWith('workbench-mobile-') && name !== CACHE).map(name => caches.delete(name)))).then(() => self.clients.claim())));
self.addEventListener('fetch', event => {
const url = new URL(event.request.url);
if (event.request.method !== 'GET' || url.origin !== self.location.origin || url.search || !FILES.includes(url.pathname)) return;
event.respondWith(fetch(event.request).then(response => {
if (response.ok) { const copy = response.clone(); event.waitUntil(caches.open(CACHE).then(cache => cache.put(event.request, copy))); }
return response;
}).catch(async () => (await caches.match(event.request)) || Response.error()));
});
`;
fs.writeFileSync(path.join(root, 'mobile-sw.js'), worker);
console.log('Mobile shell built: ' + list.length + ' allowed assets; API and project data are never cached.');
@@ -0,0 +1,46 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
// Development-only provenance recipe. Runtime code imports the resulting JSON;
// it neither trusts the QA directory nor learns new executable inputs on launch.
const evidence='docs/original-purge-load-evidence',raw=fs.readFileSync(path.join(evidence,'manifest.json'));
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
assert.equal(sha(raw),'acabdce397139dcd59cbe7f66229a1353d4f95a5ceb7a555977e544b17ea1066');
const manifest=JSON.parse(raw),root=process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT;
assert.ok(root&&path.isAbsolute(root));
const prefix=path.resolve(root)+path.sep,files=new Map();
const identify=file=>{const raw=fs.readFileSync(file);return {relative:path.relative(root,file).replaceAll('\\','/'),bytes:raw.length,sha256:sha(raw)};};
for(const input of manifest.loadedModuleInputs.filter(input=>input.path.startsWith(prefix))){
assert.equal(sha(fs.readFileSync(path.join(evidence,input.snapshot))),input.sha256);
const identity=identify(input.path);assert.equal(identity.sha256,input.sha256);files.set(identity.relative,identity);
// Node package resolution reads these metadata before source loading.
for(let parent=path.dirname(input.path);parent.startsWith(prefix)||parent===root;parent=path.dirname(parent)){
const file=path.join(parent,'package.json');if(fs.existsSync(file)){const item=identify(file);files.set(item.relative,item);}
if(parent===root)break;
}
}
for(const relative of ['packages/bundle/sdk-minimal/cordis.patch.yml','pnpm-lock.yaml']){
const input=identify(path.join(root,relative));files.set(relative,input);
}
const nativePackage='node_modules/.pnpm/node-addon-require-builtin-win32-x64-msvc@0.1.9/node_modules/node-addon-require-builtin-win32-x64-msvc';
const native=identify(path.join(root,nativePackage,'prebuilt/win32-x64-msvc-napi-v9.node'));
assert.equal(native.sha256,'ead441d11202126827a789a7eb88e79abe8f7f374b16e7273c4244225c8d6c2b');
for(const relative of ['prebuilds.json','prebuilt/win32-x64-msvc-napi-v9.node']){
const input=identify(path.join(root,nativePackage,relative));files.set(input.relative,input);
}
const koffi=identify(path.join(root,'node_modules/.pnpm/@koromix+koffi-win32-x64@3.1.1/node_modules/@koromix/koffi-win32-x64/win32_x64/koffi.node'));
assert.equal(koffi.sha256,'eb0587c804bb76262968bf83028528da4dc2d4322f558845cce205c709e2ba20');files.set(koffi.relative,koffi);
const upstream=manifest.upstreamInputs.map(({relative,bytes,sha256,snapshot})=>{
assert.equal(sha(fs.readFileSync(path.join(evidence,snapshot))),sha256);return {relative,bytes,sha256};
}).sort((a,b)=>a.relative.localeCompare(b.relative,'en'));
const lock={schemaVersion:1,purgeVersion:'1.1.78',harnessVersion:'0.2.1-rc.2',
provenance:{manifestSha256:sha(raw),sourceCommit:manifest.sourceCommit,scope:'Observed JS/JSON plus resolution metadata and explicit native require-builtin input.',
nativePeEvidenceIds:['ev_4a114ba373a5039c34e7fcdad6b9202b42d00f16cd4ae6d80304feb4d93cc19c','ev_b9670d77723678e6c17415368494a06583872fe1e41bd739d795c0c6a20ddca2']},
original:upstream,harness:[...files.values()].sort((a,b)=>a.relative.localeCompare(b.relative,'en')),
nativeAddons:[{...native,staticImports:['KERNEL32.dll'],staticDelayImports:['node.exe']},
{...koffi,staticImports:['KERNEL32.dll','ADVAPI32.dll'],staticDelayImports:['NODE.EXE']}]};
const output=process.argv[2]??'src/core/engines/original-purge-lock.json';assert.equal(fs.existsSync(output),false);
fs.writeFileSync(output,JSON.stringify(lock,null,2)+'\n',{flag:'wx'});
console.log(JSON.stringify({output,original:lock.original.length,harness:lock.harness.length,sha256:sha(fs.readFileSync(output))}));
@@ -0,0 +1,19 @@
import { build } from 'esbuild';
import fs from 'node:fs';
// Bundled CommonJS dependencies (QR PNG encoder) still import Node builtins.
const nodeRequire = { js: "import { createRequire as __awbCreateRequire } from 'node:module'; const require = __awbCreateRequire(import.meta.url);" };
fs.mkdirSync('dist-server', { recursive: true });
await build({ entryPoints: ['src/server/index.mjs'], outfile: 'dist-server/server.mjs', bundle: true,
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof', banner: nodeRequire });
await build({ entryPoints: ['src/server/hot-upgrade.mjs'], outfile: 'dist-server/hot-upgrade.mjs', bundle: true,
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof', banner: nodeRequire });
await build({ entryPoints: ['src/desktop/host-cli.mjs'], outfile: 'dist-server/host-launcher.mjs', bundle: true,
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' });
await build({ entryPoints: ['src/desktop/install-cli.mjs'], outfile: 'dist-server/install-manager.mjs', bundle: true,
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' });
fs.mkdirSync('dist-desktop', { recursive: true });
await build({ entryPoints: ['src/desktop/main.mjs'], outfile: 'dist-desktop/main.cjs', bundle: true, external: ['electron'],
platform: 'node', target: 'node24', format: 'cjs', sourcemap: false, legalComments: 'eof' });
await build({ entryPoints: ['src/desktop/preload.cjs'], outfile: 'dist-desktop/preload.cjs', bundle: true, external: ['electron'],
platform: 'node', target: 'node24', format: 'cjs', sourcemap: false, legalComments: 'eof' });
console.log('Server bundle built.');
@@ -0,0 +1,35 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
export function planBrowserBundle(appRoot) {
const lock = JSON.parse(fs.readFileSync(path.join(appRoot, 'package-lock.json'), 'utf8'));
const packages = ['playwright', 'playwright-core'].map(name => {
const root = path.join(appRoot, 'node_modules', name), meta = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const declaration = lock.packages['node_modules/' + name];
if (meta.version !== '1.64.1' || declaration.version !== meta.version || !declaration.integrity) throw new Error('Portable browser packages must match locked Playwright 1.64.1.');
if (!fs.existsSync(path.join(root, 'LICENSE'))) throw new Error('The browser package requires its original LICENSE.');
return { name, version: meta.version, root, integrity: declaration.integrity };
});
return { version: '1.64.1', packages };
}
export function copyBrowserBundle(runtimeDirectory, plan) {
const runtime = path.resolve(runtimeDirectory), output = path.join(runtime, 'node_modules'), packages = [];
const copy = (root, destination, relative = '') => {
const records = [];
for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
if (entry.isSymbolicLink()) throw new Error('Browser runtime input cannot be a link.');
const file = path.join(relative, entry.name), target = path.resolve(destination, file);
if (!target.startsWith(output + path.sep)) throw new Error('Browser bundle escaped the owned runtime.');
if (entry.isDirectory()) { fs.mkdirSync(target, { recursive: true }); records.push(...copy(root, destination, file)); continue; }
const bytes = fs.readFileSync(path.join(root, file)); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, bytes);
records.push({ path: file.replaceAll('\\', '/'), bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') });
}
return records;
};
for (const pkg of plan.packages) packages.push({ name: pkg.name, version: pkg.version, integrity: pkg.integrity,
files: copy(pkg.root, path.join(output, pkg.name)) });
const result = { schemaVersion: 1, kind: 'workbench-browser-runtime', playwrightVersion: plan.version, browser: 'local Microsoft Edge',
scope: 'win32-x64 static build checks; browser executable remains the locally installed Edge', packages };
fs.writeFileSync(path.join(runtime, 'BROWSER-RUNTIME.json'), JSON.stringify(result, null, 2) + '\n'); return result;
}
@@ -0,0 +1,51 @@
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
const digest = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
export function planDesktopBundle(root) {
const meta = JSON.parse(fs.readFileSync(path.join(root, 'node_modules/electron/package.json'), 'utf8'));
if (meta.version !== '45.2.0') throw new Error('Desktop packaging requires the fixed Electron 45.2.0 runtime.');
const installed = path.join(root, 'node_modules/electron/dist');
const directory = fs.existsSync(path.join(installed, 'electron.exe')) ? installed : path.join(root, 'runtime/electron');
const executable = path.join(directory, 'electron.exe');
if (!fs.existsSync(executable) || digest(executable) !== '010ea51bfb528c8143513439aa93fb40754403daa2023f9decd4517da71706ab') throw new Error('The actual Windows Electron runtime differs from the fixed binary.');
for (const file of ['LICENSE', 'LICENSES.chromium.html']) if (!fs.existsSync(path.join(directory, file))) throw new Error('Electron runtime license missing.');
return { directory, version: meta.version, sha256: digest(executable), bytes: fs.statSync(executable).size };
}
export function buildNativeLauncher(root, output) {
const compiler = path.join(process.env.SystemRoot || 'C:\\Windows', 'Microsoft.NET/Framework64/v4.0.30319/csc.exe');
if (!fs.existsSync(compiler)) throw new Error('The Windows .NET Framework compiler is required to build the fixed desktop launcher.');
fs.mkdirSync(path.dirname(output), { recursive: true });
const inputs = { compiler: digest(compiler), source: digest(path.join(root, 'src/desktop/Launcher.cs')), icon: digest(path.join(root, 'public/workbench-icon.ico')) };
const recordFile = output + '.build.json';
if (fs.existsSync(output) && fs.existsSync(recordFile)) {
const cached = JSON.parse(fs.readFileSync(recordFile, 'utf8'));
if (JSON.stringify(cached.inputs) === JSON.stringify(inputs) && cached.sha256 === digest(output)) return cached;
}
try { execFileSync(compiler, ['/nologo', '/target:winexe', '/platform:x64', '/optimize+', '/utf8output',
'/reference:System.Web.Extensions.dll', '/reference:System.Windows.Forms.dll', '/win32icon:' + path.join(root, 'public/workbench-icon.ico'),
'/out:' + output, path.join(root, 'src/desktop/Launcher.cs')], { cwd: root, windowsHide: true, timeout: 30000, stdio: 'pipe' }); }
catch (error) { fs.writeFileSync(output + '.compile-failure.txt', Buffer.concat([error.stdout ?? Buffer.alloc(0), error.stderr ?? Buffer.alloc(0)])); throw error; }
const record = { bytes: fs.statSync(output).size, sha256: digest(output), inputs, compiler: 'Windows .NET Framework C# compiler; source-bound cached original output, no deterministic-build claim.' };
fs.writeFileSync(recordFile, JSON.stringify(record, null, 2)); return record;
}
export function copyDesktopBundle(root, output, plan, { source = false, launcher = null } = {}) {
if (source && digest(path.join(plan.directory, 'resources/default_app.asar')) !== 'eac55d6cfcf4eab7e31a45356567f549ef7eb669e3699226b48a8492ad34f510') {
throw new Error('The source Electron runtime requires its fixed default application loader.');
}
const destination = path.join(output, source ? 'runtime/electron' : 'desktop');
fs.cpSync(plan.directory, destination, { recursive: true, filter: file => source || path.basename(file) !== 'default_app.asar' });
if (!source) {
fs.renameSync(path.join(destination, 'electron.exe'), path.join(destination, 'AgentWorkbench.exe'));
const app = path.join(destination, 'resources/app'); fs.mkdirSync(app, { recursive: true });
fs.writeFileSync(path.join(app, 'package.json'), JSON.stringify({ name: 'agent-workbench-desktop', version: JSON.parse(fs.readFileSync(path.join(root, 'package.json'))).version, main: 'main.cjs' }) + '\n');
fs.writeFileSync(path.join(app, 'main.cjs'), "require('../../../dist-desktop/main.cjs');\n");
if (launcher) fs.copyFileSync(launcher, path.join(output, 'AgentWorkbench.exe'));
}
const identity = { version: plan.version, sha256: plan.sha256, bytes: plan.bytes, executable: source ? 'runtime/electron/electron.exe' : 'desktop/AgentWorkbench.exe',
scope: 'Fixed original Windows Electron runtime, full license texts, isolated application loader and native bootstrap; original executable hash unchanged.' };
fs.writeFileSync(path.join(output, 'DESKTOP-RUNTIME.json'), JSON.stringify(identity, null, 2) + '\n');
return identity;
}
@@ -0,0 +1,71 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { REA_VERSION, REA_PROTOCOL, resolveReaInstallation } from '../src/core/tools/rea-adapter.mjs';
const digest = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
const inside = (root, filename) => path.resolve(filename).startsWith(path.resolve(root) + path.sep);
const packageMetadata = root => JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
export function planReaBundle(appRoot) {
const installation = resolveReaInstallation(appRoot);
if (installation.status !== 'available') throw new Error('REA release dependency is unavailable: ' + installation.message);
const modules = path.dirname(installation.packageRoot), sourceRoot = path.dirname(modules);
const originalLock = path.join(sourceRoot, 'package-lock.json'), lockPath = fs.existsSync(originalLock) ? originalLock : path.join(sourceRoot, 'REA-PACKAGE-LOCK.json');
if (path.basename(modules) !== 'node_modules' || !fs.existsSync(lockPath)) throw new Error('Use the isolated, locked REA production installation when packaging.');
const lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
if (lock.packages?.['node_modules/rea-agents']?.version !== REA_VERSION || lock.packages['']?.dependencies?.['rea-agents'] !== REA_VERSION) throw new Error('REA installation lock does not match the fixed release contract.');
const packages = [], absentOptional = [];
for (const [relative, expected] of Object.entries(lock.packages)) {
if (!relative.startsWith('node_modules/')) continue;
const absolute = path.resolve(sourceRoot, relative);
if (!inside(modules, absolute)) throw new Error('REA dependency escapes its installation: ' + relative);
if (!fs.existsSync(path.join(absolute, 'package.json'))) {
if (expected.optional || expected.dev) { if (expected.optional) absentOptional.push(relative); continue; }
throw new Error('REA required installed dependency is missing: ' + relative);
}
if (expected.dev) throw new Error('REA release input must contain only production dependencies: ' + relative);
if (fs.lstatSync(absolute).isSymbolicLink() || !inside(modules, fs.realpathSync.native(absolute))) throw new Error('REA release dependencies must be regular contained directories.');
const metadata = packageMetadata(absolute);
if (metadata.version !== expected.version) throw new Error('REA installed dependency declaration differs from its lock: ' + relative);
const licenseFiles = fs.readdirSync(absolute).filter(name => /^(licen[cs]e|copying)([.-].*)?$/i.test(name) && fs.statSync(path.join(absolute, name)).isFile());
packages.push({ path: relative, name: metadata.name, version: metadata.version, license: metadata.license ?? expected.license ?? null,
integrity: expected.integrity ?? null, licenseFiles });
}
const topLevel = packages.filter(item => !packages.some(parent => item !== parent && item.path.startsWith(parent.path + '/')));
if (!packages.some(item => item.name === 'rea-agents' && item.version === REA_VERSION)) throw new Error('REA package is absent from the installed production graph.');
return { installation, sourceRoot, lockPath, lockSha256: digest(lockPath), packages, topLevel, absentOptional, builtAt: new Date().toISOString() };
}
export function copyReaBundle(destinationRuntime, plan) {
fs.mkdirSync(destinationRuntime, { recursive: true });
for (const item of plan.topLevel) {
const destination = path.join(destinationRuntime, item.path);
if (!inside(destinationRuntime, destination)) throw new Error('REA destination is outside the new release runtime.');
if (fs.existsSync(destination)) throw new Error('Refusing to overwrite a runtime dependency: ' + item.path);
fs.cpSync(path.join(plan.sourceRoot, item.path), destination, { recursive: true, filter: file => {
if (fs.lstatSync(file).isSymbolicLink()) throw new Error('REA runtime contains an unsupported link: ' + file);
return true;
} });
}
fs.copyFileSync(plan.lockPath, path.join(destinationRuntime, 'REA-PACKAGE-LOCK.json'));
const files = [];
const walk = relative => {
for (const entry of fs.readdirSync(path.join(destinationRuntime, relative), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
const filename = path.join(relative, entry.name);
if (entry.isDirectory()) walk(filename);
else if (entry.isFile()) files.push({ path: filename.replaceAll('\\', '/'), bytes: fs.statSync(path.join(destinationRuntime, filename)).size,
sha256: digest(path.join(destinationRuntime, filename)) });
else throw new Error('REA runtime contains a non-regular entry: ' + filename);
}
};
for (const item of plan.topLevel) walk(item.path);
const manifest = { schemaVersion: 1, name: 'rea-agents', version: REA_VERSION, protocolVersion: REA_PROTOCOL, builtAt: plan.builtAt,
installationLock: { path: 'REA-PACKAGE-LOCK.json', sha256: plan.lockSha256 }, packages: plan.packages,
absentOptional: plan.absentOptional, files,
identityScope: 'Copied installed production package declarations and file snapshots; MCP handshake and static operations are independently verified.',
capabilities: ['javascript-asar-static', 'pe-imports-static', 'pe-resources-static'] };
fs.writeFileSync(path.join(destinationRuntime, 'REA-RUNTIME.json'), JSON.stringify(manifest, null, 2) + '\n');
return { version: manifest.version, protocolVersion: manifest.protocolVersion, packages: manifest.packages.length,
files: files.length, bytes: files.reduce((sum, item) => sum + item.bytes, 0), lockSha256: plan.lockSha256 };
}
@@ -0,0 +1,137 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { randomUUID, createHash } from 'node:crypto';
import { _electron, expect } from 'playwright/test';
import { createRequestHandler, createSessionPublisher } from '../src/server/app.mjs';
import { hostAuthority } from '../src/core/desktop/host-authority.mjs';
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
import { projectEnvironment } from '../src/core/process-environment.mjs';
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
export async function desktopProjectQa({ store, provider, runtime, sample, kind }) {
const appRoot = path.resolve(process.env.AGENT_WORKBENCH_DESKTOP_QA_APP_ROOT || process.cwd()), server = http.createServer(), clients = new Set(), token = randomUUID();
runtime.appDirectory = appRoot; store.claimRuntime(); store.on('update', createSessionPublisher(clients));
server.on('request', createRequestHandler({ appDirectory: appRoot, server, store, provider, runtime, token, clients, started: Date.now(), getPort: () => server.address().port, shutdown: () => {} }));
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const authority = hostAuthority({ appDirectory: appRoot, server, store, provider, runtime }); authority.initialize();
let application, page, selected; const events = [], errors = [], screenshots = [];
async function launch() {
const executable = desktopExecutableIdentity(appRoot).path, packaged = executable.toLowerCase().endsWith('agentworkbench.exe');
application = await _electron.launch({ executablePath: executable,
args: [...(packaged ? [] : [path.join(appRoot, 'dist-desktop/main.cjs')]), '--app-root', appRoot, '--data-root', store.directory, '--node', process.execPath, '--port', String(server.address().port), '--hidden-window'],
cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
page = await application.firstWindow(); page.on('pageerror', error => errors.push(error.message));
await page.locator('.connection.connected').waitFor({ timeout: 30000 });
if (selected) await select(selected);
}
async function select(session) {
selected = session;
const project = page.getByRole('combobox', { name: '当前项目', exact: true });
if (!await project.isVisible()) await page.getByRole('button', { name: '展开项目栏', exact: true }).click();
await project.selectOption(session.projectId);
await expect.poll(() => page.evaluate(() => localStorage.getItem('awb-session')), { timeout: 20000 }).toBe(session.id);
}
async function closeInspector() { const close = page.getByRole('button', { name: '关闭检视区', exact: true }); if (await close.isVisible().catch(() => false)) await close.click(); }
async function review(session, ids) {
await select(session); await closeInspector();
const prepared = [...store.core.change_set.values()].find(value => value.sessionId === session.id && value.status === 'prepared' && JSON.stringify(value.files.map(file => file.changeId).sort()) === JSON.stringify(ids.slice().sort()));
if (prepared) {
await page.getByRole('button', { name: '隔离协作', exact: true }).click();
await page.getByRole('button', { name: '打开父工程变更集审查', exact: true }).click();
await page.getByRole('button', { name: '审查变更集', exact: true }).click();
} else {
if (await page.getByRole('button', { name: '查看改动', exact: true }).isVisible()) await page.getByRole('button', { name: '查看改动', exact: true }).click();
else await page.locator('.inspector-tabs').getByRole('button', { name: /^改动/ }).click();
await page.getByRole('button', { name: '组合审查', exact: true }).click();
await page.getByRole('dialog', { name: '选择要一起审查的提案', exact: true }).getByRole('button', { name: '封存审查范围', exact: true }).click();
}
const dialog = page.getByRole('dialog', { name: '多文件变更集审查', exact: true });
const confirm = dialog.getByRole('button', { name: '确认应用全部 ' + ids.length + ' 项', exact: true }); await confirm.waitFor();
const matching = [...store.core.change_set.values()].filter(value => value.sessionId === session.id && value.status !== 'completed' && JSON.stringify(value.files.map(file => file.changeId).sort()) === JSON.stringify(ids.slice().sort()));
assert.equal(matching.length, 1); const set = matching[0];
const response = page.waitForResponse(value => new URL(value.url()).pathname === '/api/sessions/' + session.id + '/change-sets/' + set.id + '/apply'
&& value.request().method() === 'POST', { timeout: 120000 });
await confirm.click(); const applied = await response;
assert.equal(applied.status(), 202, 'Original desktop apply request was rejected');
const operation = runtime.changeSetManager().active.get(set.id);
if (operation) await operation.promise;
assert.equal(set.status, 'completed', JSON.stringify({ status: set.status, summary: set.summary, requiresVerification: set.requiresVerification }));
await expect(dialog).toContainText('全部应用完成', { timeout: 20000 }); await page.keyboard.press('Escape');
assert.equal(set.status, 'completed'); events.push({ action: 'actual-desktop-file-review', taskId: session.taskId, changeSetId: set.id, fingerprint: set.fingerprint, paths: set.files.map(value => value.path) }); return set;
}
async function approve(session, approval) {
await select(session); await closeInspector();
const button = page.getByRole('button', { name: '确认执行', exact: true }); await button.waitFor({ timeout: 20000 });
assert.equal(session.approvals.filter(value => value.status === 'pending').length, 1); assert.equal(session.approvals.find(value => value.status === 'pending').id, approval.id);
await button.click(); await expect.poll(() => approval.status).toBe('approved'); events.push({ action: 'actual-desktop-original-approval', approvalId: approval.id, taskId: session.taskId });
}
async function cycle(session, label) {
await select(session); const identity = authority.identity(), eventSeq = session.eventSeq, taskId = session.taskId, runId = session.runId;
const originalEvents = () => {
const events = []; let cursor = 0;
while (cursor < eventSeq) {
const chunk = store.eventsAfter(cursor, { sessionId: session.id, limit: 500 });
events.push(...chunk.events.filter(value => value.seq <= eventSeq));
if (!chunk.hasMore || chunk.nextCursor >= eventSeq) break;
assert.ok(chunk.nextCursor > cursor); cursor = chunk.nextCursor;
}
return events;
};
const retainedEvents = originalEvents(); assert.equal(retainedEvents.at(-1).seq, eventSeq);
const completed = () => [...store.core.tool.values()].filter(value => value.sessionId === session.id && value.state === 'completed');
const prior = hash(Buffer.from(JSON.stringify(completed()))), approvals = session.approvals.map(value => ({ id: value.id, status: value.status }));
await application.close(); application = null;
assert.equal(runtime.isActive(session.id), true); assert.equal(authority.identity().instanceId, identity.instanceId); assert.equal(process.pid, identity.pid);
await launch(); assert.equal(session.taskId, taskId); assert.equal(session.runId, runId); assert.ok(session.eventSeq >= eventSeq); assert.deepEqual(originalEvents(), retainedEvents);
const replay = await page.evaluate(async ({ sessionId, cursor }) => {
const bootstrap = await (await fetch('/api/bootstrap')).json();
const response = await fetch('/api/events/history?session=' + encodeURIComponent(sessionId) + '&after=' + cursor + '&limit=500', { headers: { 'x-workbench-token': bootstrap.token } });
if (!response.ok) throw Error('Original desktop event replay failed (' + response.status + ')'); return response.json();
}, { sessionId: session.id, cursor: eventSeq - 1 });
assert.deepEqual(replay.events[0], retainedEvents.at(-1)); assert.ok(replay.events.every((value, index) => !index || value.seq > replay.events[index - 1].seq));
assert.equal(hash(Buffer.from(JSON.stringify(completed()))), prior); assert.deepEqual(session.approvals.map(value => ({ id: value.id, status: value.status })), approvals);
events.push({ action: label, hostPid: process.pid, taskId, runId, eventSeq, reopenedEventSeq: session.eventSeq, replayCursor: replay.nextCursor,
retainedEvents: retainedEvents.length, retainedEventsSha256: hash(Buffer.from(JSON.stringify(retainedEvents))), instanceId: identity.instanceId, completedToolSha256: prior, approvals });
}
async function capture(session, label) {
await select(session); await closeInspector(); await page.getByRole('button', { name: '隔离协作', exact: true }).click();
for (const width of [1440, 390]) {
const native = await application.browserWindow(page); await native.evaluate((value, width) => { value.showInactive(); value.setContentSize(width, 900); }, width);
await expect.poll(() => page.evaluate(() => innerWidth)).toBe(width);
const filename = path.join(sample, kind + '-' + label + '-' + width + '.png'); await page.screenshot({ path: filename }); fs.writeFileSync(filename + '.html', await page.content());
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); screenshots.push({ file: filename, width, sha256: hash(fs.readFileSync(filename)) });
}
await (await application.browserWindow(page)).evaluate(value => value.setContentSize(1440, 1000));
// Electron resize and React's responsive state settle independently.
// Await both before querying a control whose accessible name changes.
await expect.poll(() => page.evaluate(() => innerWidth)).toBe(1440);
await expect(page.getByRole('button', { name: '关闭检视区', exact: true })).toBeHidden();
await page.keyboard.press('Escape'); await expect(page.getByRole('dialog', { name: '隔离协作', exact: true })).toBeHidden();
await closeInspector();
}
await launch();
return { select, review, approve, cycle, capture, events, screenshots, errors, get page() { return page; },
async resize(width, height) { await (await application.browserWindow(page)).evaluate((value, size) => { value.showInactive(); value.setContentSize(size.width, size.height); }, { width, height }); await expect.poll(() => page.evaluate(() => innerWidth)).toBe(width); },
async download(filename, trigger) {
const id = randomUUID();
await application.evaluate(({ session }, { id, filename }) => {
globalThis.workbenchQaDownloads ??= {};
globalThis.workbenchQaDownloads[id] = { state: 'waiting' };
session.defaultSession.once('will-download', (_event, item) => {
const value = globalThis.workbenchQaDownloads[id]; value.suggestedFilename = item.getFilename(); value.state = 'started';
item.setSavePath(filename); // Actual Electron DownloadItem; only the owned destination selection is a QA fixture.
item.once('done', (_event, state) => { value.state = state; value.bytes = item.getReceivedBytes(); value.totalBytes = item.getTotalBytes(); });
});
}, { id, filename });
await trigger(); await expect.poll(() => application.evaluate((_electron, id) => globalThis.workbenchQaDownloads[id].state, id), { timeout: 30000 }).toBe('completed');
const value = await application.evaluate((_electron, id) => globalThis.workbenchQaDownloads[id], id);
assert.equal(value.bytes, value.totalBytes); assert.equal(fs.statSync(filename).size, value.bytes);
events.push({ action: 'actual-electron-native-download', ...value, file: filename, sha256: hash(fs.readFileSync(filename)), scope: 'Actual DownloadItem and transferred bytes; own output path chosen by QA without exercising the Windows save dialog.' });
return value;
},
scope: 'Real Electron renderer and fixed native main/preload; own in-process Node fixture host, actual native Harness/HTTP/check/Git. The whole fixture host is never exited from its desktop UI.',
async failure(error) { if (!page || page.isClosed()) return; const filename = path.join(sample, kind + '-desktop-failure'); fs.writeFileSync(filename + '.html', await page.content()); fs.writeFileSync(filename + '.json', JSON.stringify({ error: error.stack, dialogs: await page.getByRole('dialog').allTextContents(), errors, events }, null, 2)); await (await application.browserWindow(page)).evaluate(value => value.showInactive()); await page.screenshot({ path: filename + '.png' }); },
async close() { await application?.close(); for (const response of clients) response.destroy(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); assert.deepEqual(errors, []); } };
}
@@ -0,0 +1,75 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
export const REQUIRED_REPORTS = Object.freeze(['docs/RESEARCH.md', 'docs/research/CURSOR-MECHANISMS.md', 'docs/research/CONTEXT-RECOVERY.md', 'docs/research/TOOL-LOOP.md']);
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
const simple = value => value.replaceAll('\\', '/');
export function createDocumentationBundle({ root, portableRoot, evidenceRoot, archiveName, sourceCommit }) {
if (!/^[a-f0-9]{40}$/.test(sourceCommit) || !/^[A-Za-z0-9._-]+\.zip$/.test(archiveName)) throw new Error('Documentation needs the fixed source commit and separate archive name.');
if (fs.existsSync(evidenceRoot)) throw new Error('Historical evidence output must be a new directory.');
const entries = [];
const walk = relative => {
for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true })) {
const next = path.posix.join(relative, entry.name);
if (entry.isSymbolicLink()) throw new Error('Documentation source cannot contain links: ' + next);
if (entry.isDirectory()) walk(next);
else if (entry.isFile()) {
const bytes = fs.readFileSync(path.join(root, next));
entries.push({ path: next, bytes: bytes.length, sha256: hash(bytes) });
} else throw new Error('Documentation source must contain regular files: ' + next);
}
};
walk('docs'); entries.sort((a, b) => a.path.localeCompare(b.path));
const byPath = new Map(entries.map(row => [row.path, row]));
for (const file of REQUIRED_REPORTS) if (!byPath.has(file)) throw new Error('Required original research report missing: ' + file);
// Text guides and original research remain offline. Large historical raw
// receipts/screenshots are independently shipped with their original paths.
const selected = new Set(entries.filter(row => /^docs\/[^/]+\.md$/.test(row.path) || /^docs\/research\/[^/]+\.(?:md|json)$/.test(row.path)).map(row => row.path));
const references = [], shipped = [];
fs.mkdirSync(evidenceRoot, { recursive: true });
for (const row of entries) {
const target = path.join(evidenceRoot, row.path); fs.mkdirSync(path.dirname(target), { recursive: true });
fs.copyFileSync(path.join(root, row.path), target);
if (hash(fs.readFileSync(target)) !== row.sha256) throw new Error('Original evidence copy differs: ' + row.path);
}
const evidenceManifest = { schema: 1, app: 'agent-workbench-evidence', sourceCommit, scope: 'Original docs tree, including all successful/failed historical evidence. No runtime execution dependency.', files: entries };
const evidenceBytes = Buffer.from(JSON.stringify(evidenceManifest, null, 2) + '\n');
fs.writeFileSync(path.join(evidenceRoot, 'MANIFEST.json'), evidenceBytes, { flag: 'wx' });
const rewrite = (file, original) => original.replace(/\]\(([^)]+)\)/g, (whole, raw) => {
const [target] = raw.split('#');
if (!target || /^[a-z]+:/i.test(target) || target.startsWith('/')) return whole;
let decoded;
try { decoded = decodeURI(target); } catch { references.push({ from: file, target, disposition: 'malformed-historical-reference' }); return whole; }
const resolved = simple(path.posix.normalize(path.posix.join(path.posix.dirname(file), decoded)));
if (!resolved.startsWith('docs/')) return whole;
const source = byPath.get(resolved);
if (!source) {
references.push({ from: file, target, disposition: 'historical-source-not-in-repository' });
return whole;
}
if (selected.has(resolved)) return whole;
references.push({ from: file, target: resolved, sha256: source.sha256, disposition: REQUIRED_REPORTS.includes(file) ? 'original-report-reference-in-evidence-archive' : 'evidence-catalog-link' });
if (REQUIRED_REPORTS.includes(file)) return whole; // Preserve all four original report bytes exactly.
const catalogue = path.posix.relative(path.posix.dirname(file), 'docs/EVIDENCE-CATALOG.md');
return '](' + catalogue + '#e-' + source.sha256.slice(0, 16) + ')';
});
for (const file of [...selected, 'README.md']) {
const original = fs.readFileSync(path.join(root, file));
const content = Buffer.from(rewrite(file, original.toString('utf8')));
const destination = path.join(portableRoot, file); fs.mkdirSync(path.dirname(destination), { recursive: true });
fs.writeFileSync(destination, content);
shipped.push({ path: file, bytes: content.length, sha256: hash(content), sourceSha256: hash(original), originalBytesPreserved: content.equals(original) });
}
const linked = new Map(references.filter(row => row.sha256).map(row => [row.target, byPath.get(row.target)]));
const catalogue = ['# 历史验收资料', '', '运行包保留离线使用说明和四份原研究报告。完整历史原件另存于配套证据包,包含原路径、SHA-256、成功与失败记录;源码包也保留完整资料。', '',
`配套归档:\`${archiveName}\``, '', `原件清单 SHA-256:\`${hash(evidenceBytes)}\``, '',
'请将证据包解压到单独目录,按其中的原 docs/ 路径查看。不要解压到受完整性核对的程序目录。缺少证据包不影响运行工作台。', ''];
for (const [file, row] of [...linked].sort(([a], [b]) => a.localeCompare(b))) catalogue.push(`<a id="e-${row.sha256.slice(0, 16)}"></a>`, `## ${file}`, '', `原件:\`${file}\` · ${row.bytes} 字节`, '', `SHA-256:\`${row.sha256}\``, '');
fs.writeFileSync(path.join(portableRoot, 'docs/EVIDENCE-CATALOG.md'), catalogue.join('\n'));
const result = { schema: 1, sourceCommit, archiveName, evidenceManifestSha256: hash(evidenceBytes), originalFiles: entries.length, originalBytes: entries.reduce((sum, row) => sum + row.bytes, 0),
shipped, references, originalReports: REQUIRED_REPORTS.map(file => byPath.get(file)), evidenceEntries: entries };
fs.writeFileSync(path.join(portableRoot, 'DOCUMENTATION.json'), JSON.stringify(result, null, 2) + '\n');
return { ...result, evidenceRoot };
}
@@ -0,0 +1,70 @@
import fs from 'node:fs';
import path from 'node:path';
// A declared wire fixture. It does not load the third-party SDK or call a model.
export function createEngineFixture(directory, options = {}) {
fs.mkdirSync(directory, { recursive: true });
const version = '0.2.1-rc.2';
const manifests = [
['apps/cli/package.json', '@deepseek-ai/dsh'],
['packages/bundle/sdk-minimal/package.json', '@deepseek-ai/dsh-sdk-minimal'],
['packages/sdk/server/package.json', '@deepseek-ai/dsh-sdk-jsonrpc-server'],
['packages/sdk/protocol/package.json', '@deepseek-ai/dsh-sdk-protocol'],
['packages/sdk/client/package.json', '@deepseek-ai/dsh-sdk-client'],
];
const write = (relative, content) => { const filename = path.join(directory, relative); fs.mkdirSync(path.dirname(filename), { recursive: true }); fs.writeFileSync(filename, content); };
for (const [relative, name] of manifests) write(relative, JSON.stringify({ name, version, type: 'module', fixture: true }));
for (const relative of ['packages/boot/cmdline/lib/index.js', 'packages/bundle/sdk-app/lib/index.js', 'packages/sdk/server/lib/index.js', 'packages/sdk/protocol/lib/index.js']) write(relative, '// Owned protocol fixture; not the actual SDK.\n');
write('packages/bundle/sdk-minimal/cordis.patch.yml', '# Owned wire-fixture profile\n');
write('pnpm-lock.yaml', '# Owned deterministic fixture identity\n');
write('apps/cli/node_modules/@deepseek-ai/cordis/package.json', JSON.stringify({ name: '@deepseek-ai/cordis', type: 'module', exports: './index.mjs', fixture: true }));
write('apps/cli/node_modules/@deepseek-ai/cordis/index.mjs', '// Owned Cordis identity fixture; never imported.\n');
write('fixture-options.json', JSON.stringify(options));
write('apps/cli/lib/bin.js', `import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createInterface } from 'node:readline';
import { randomUUID } from 'node:crypto';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
const options = JSON.parse(fs.readFileSync(path.join(root, 'fixture-options.json'), 'utf8'));
const patch = JSON.parse(fs.readFileSync(process.argv[process.argv.indexOf('--patch') + 1], 'utf8'));
const config = patch[0].insert[0].config;
const audit = value => fs.appendFileSync(path.join(root, 'wire.jsonl'), JSON.stringify(value) + '\\n');
const send = value => process.stdout.write(JSON.stringify(value) + '\\n');
audit({ type: 'launch', cwd: process.cwd(), nodeOptionsInherited: !!process.env.NODE_OPTIONS,
secretInherited: !!process.env.OWNED_ENGINE_TEST_SECRET, profile: process.argv[process.argv.indexOf('--profile') + 1] });
if (options.mode !== 'no-ready') setTimeout(() => {
fs.writeFileSync(config.marker, JSON.stringify({ schemaVersion: 1, nonce: options.mode === 'bad-ready' ? 'wrong' : config.nonce,
pid: process.pid, signal: 'appReady', readyAt: new Date().toISOString() }), { flag: 'wx' });
}, options.readyDelayMs ?? 0);
const reader = createInterface({ input: process.stdin });
reader.on('line', async line => {
const value = JSON.parse(line); audit({ type: 'wire', value });
if (!value.method) return;
const params = value.params ?? {};
let result = {};
if (value.method === 'initialize') {
if (!fs.existsSync(config.marker)) { send({ jsonrpc: '2.0', id: value.id, error: { code: -32603, message: 'initialize before appReady' } }); return; }
if (options.mode === 'hang-init') return;
if (options.mode === 'malformed') { process.stdout.write('{broken-json}\\n'); return; }
if (options.mode === 'reverse-request') send({ jsonrpc: '2.0', id: 'reverse-control', method: 'approve-command', params: { command: 'fixture-never-executed' } });
if (options.mode === 'unowned-event') send({ jsonrpc: '2.0', method: 'session.status', params: { sessionId: randomUUID(), status: 'idle' } });
if (options.mode === 'model-request') await fetch(process.env.DEEPSEEK_BASE_URL + '/chat/completions', { method: 'POST', body: '{}' });
result = { serverInfo: { name: 'deepseek-harness-sdk-runtime', version: options.mode === 'wrong-version' ? '9.9' : '0.0.1' } };
} else if (value.method === 'session/working-directory/get') {
if (options.mode === 'change-input') fs.appendFileSync(path.join(root, 'packages/boot/cmdline/lib/index.js'), '// changed\\n');
if (options.mode === 'change-workspace') fs.writeFileSync(path.join(process.cwd(), 'README.md'), 'fixture mutated');
result = { cwd: options.mode === 'wrong-cwd' ? root : process.cwd() };
} else if (['session/wait', 'session/resume', 'session/cancel'].includes(value.method)) {
send({ jsonrpc: '2.0', id: value.id, error: { code: -32603, message: value.method === 'session/cancel'
? 'unknown DeepSeek Harness SDK runtime method: session/cancel' : 'unknown SDK session: ' + params.sessionId } }); return;
} else if (value.method !== 'shutdown') {
send({ jsonrpc: '2.0', id: value.id, error: { code: -32601, message: 'unknown fixture method' } }); return;
}
send({ jsonrpc: '2.0', id: value.id, result });
if (value.method === 'shutdown') setImmediate(() => process.exit(0));
});
process.stdin.on('end', () => process.exit(0));
`);
return directory;
}
@@ -0,0 +1,28 @@
"""Generate the product's deterministic original bracket/workbench icon (PNG and ICO)."""
import pathlib
import struct
import zlib
size = 256
rows = []
for y in range(size):
row = bytearray([0])
for x in range(size):
color = (28, 64, 115, 255)
if (46 <= x < 64 and 64 <= y < 192 or 46 <= x < 98 and (64 <= y < 82 or 174 <= y < 192)
or 192 <= x < 210 and 64 <= y < 192 or 158 <= x < 210 and (64 <= y < 82 or 174 <= y < 192)):
color = (238, 246, 255, 255)
if 100 <= x < 156 and 119 <= y < 137:
color = (105, 182, 247, 255)
row.extend(color)
rows.append(bytes(row))
def chunk(tag, value):
return struct.pack('>I', len(value)) + tag + value + struct.pack('>I', zlib.crc32(tag + value))
png = (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0))
+ chunk(b'IDAT', zlib.compress(b''.join(rows), 9)) + chunk(b'IEND', b''))
root = pathlib.Path(__file__).resolve().parent.parent / 'public'
(root / 'workbench-icon.png').write_bytes(png)
(root / 'workbench-icon.ico').write_bytes(struct.pack('<HHH', 0, 1, 1) + struct.pack('<BBBBHHII', 0, 0, 0, 0, 1, 32, len(png), 22) + png)
print('Original desktop icon generated: PNG and ICO, 256 × 256.')
@@ -0,0 +1,149 @@
"""Read a pinned, clean public source checkout; never import or run its code."""
import argparse
import hashlib
import json
from pathlib import Path
import subprocess
PIN = "2d0b22e0b3554686e1e4131f8bdc568ef768e060"
PRODUCT_PIN = "676fc554"
URL = "https://github.com/huiliyi37/Tianshu-harness"
# Identifiers are used by the research report. Empty needles anchor at line one.
SOURCES = [
("S01", "package.json", '"version"'),
("S02", "LICENSE", ""),
("S03", "README.md", "**提交、验证、审查分离的交付**"),
("S04", "src/agent/runtime-hooks.ts", "export type RuntimeHookPhase"),
("S05", "src/agent/create-runtime-hooks.ts", "export function createDefaultRuntimeHooks"),
("S06", "src/agent/loop-factory.ts", "const hooks = createDefaultRuntimeHooks"),
("S07", "src/agent/turn-perception.ts", ""),
("S08", "src/agent/tool-execution.ts", "export class ToolExecutionController"),
("S09", "src/agent/turn-orchestrator.ts", ""),
("S10", "src/context/task-contract.ts", "export interface TaskContract"),
("S11", "src/agent/evidence-obligation.ts", "export type ObligationState"),
("S12", "src/agent/obligation-tracker.ts", "export class ObligationTracker"),
("S13", "src/agent/loop.ts", "captureAcceptance(items:"),
("S14", "src/agent/advisory-bus.ts", "export class AdvisoryBus"),
("S15", "src/agent/runtime-advice-facts.ts", ""),
("S16", "src/agent/convergence-detector.ts", "const effectiveScore ="),
("S17", "src/agent/convergence-message.ts", ""),
("S18", "src/agent/score-history.ts", ""),
("S19", "src/tools/write-tool-helpers.ts", ""),
("S20", "src/agent/exploration-stall.ts", ""),
("S21", "src/agent/__tests__/convergence-detector.test.ts", ""),
("S22", "src/agent/delivery-gate-v2.ts", ""),
("S23", "src/agent/deliver-task.ts", ""),
("S24", "src/agent/evidence.ts", ""),
("S25", "src/agent/verification-snapshot.ts", ""),
("S26", "src/agent/verification-scope-current.ts", ""),
("S27", "src/agent/tool-pipeline.ts", "export function executeToolUse("),
("S28", "src/agent/approval-input-boundary.ts", ""),
("S29", "src/prompt/engine.ts", "export class PromptEngine"),
("S30", "src/agent/request-context-controller.ts", "export class RequestContextController"),
("S31", "src/agent/context-budget-preparation.ts", "export async function prepareContextRequest"),
("S32", "src/agent/compact-boundary-coordinator.ts", ""),
("S33", "src/context/request-budget.ts", ""),
("S34", "src/tools/tool-preset.ts", "minimal 36 / 26"),
("S35", "src/tools/default-registry.ts", ""),
("S36", "src/agent/tool-surface.ts", "export function describeToolSurface"),
("S37", "src/agent/work-order.ts", "const workerBudgetSchema"),
("S38", "src/agent/worker-runtime.ts", "export function createWorkerRuntimeFactory"),
("S39", "src/agent/worker-session.ts", "async function runWorkerSessionImpl"),
("S40", "src/agent/hands-session.ts", "const gateOn ="),
("S41", "src/agent/worker-write-gate.ts", "export async function evaluateWorkerWriteGate"),
("S42", "src/agent/worker-objective-gate.ts", "export function reconcileWithObjective"),
("S43", "src/agent/coordinator.ts", "result: reconcileWithObjective(order"),
("S44", "src/model/model-binding.ts", "export function resolveModelBinding"),
("S45", "src/config/provider-keys.ts", "export function findModelOwner"),
("S46", "src/api/fallback-client.ts", "getMainPrefixProof?.() ||"),
("S47", "src/memory/formation-policy.ts", ""),
("S48", "src/memory/essence-gate.ts", "export async function runEssenceGate"),
("S49", "src/memory/unified-memory.ts", "export function recallMemoryEntries"),
("S50", "src/agent/hooks/essence-gate-hook.ts", ""),
("S51", "src/agent/skill-distill.ts", "export function renderSkillDraftMarkdown"),
("S52", "src/agent/hooks/skill-distill-hook.ts", ""),
("S53", "src/skills/skill-loader.ts", "Two tiers:"),
("S54", "src/mcp/manager.ts", "export class McpManager"),
("S55", "src/plugins/plugin-loader.ts", "export async function initializePlugins"),
("S56", "src/tools/computer-use/bridge.ts", ""),
("S57", "src/tools/computer-use/stub.ts", ""),
("S58", "docs/architecture-overview.md", ""),
("S59", "docs/reference/observability-harness.md", ""),
("S60", "docs/CVM运行时对Agent模型的实证影响.md", "版权与许可"),
("S61", "docs/reference/cvm-cognitive-runtime.md", "版权与许可"),
("S62", "src/cli/entry.ts", ""),
("S63", "src/main.ts", ""),
]
PRODUCT = [
"src/server/runtime.mjs", "src/core/context/working-set.mjs",
"src/core/context/request-plan.mjs", "src/core/context/delivery-progress.mjs",
"src/core/tasks/task-plan-manager.mjs", "src/core/tasks/worker-manager.mjs",
"src/core/git-delivery.mjs", "src/core/models/model-hub.mjs",
"src/core/models/protocols.mjs", "src/core/memory/project-memory.mjs",
"src/core/evaluation/evaluation-manager.mjs", "src/core/browser/browser-manager.mjs",
"src/shared/contracts/task-plans.mjs", "docs/PLAN-1.25.md",
]
def git(root, *args):
return subprocess.check_output(["git", "-C", str(root), *args])
def digest(root, rel):
data = (root / rel).read_bytes()
return {"path": rel, "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(),
"lines": len(data.decode("utf-8").splitlines())}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
source = args.source.resolve()
product = Path(__file__).resolve().parents[1]
assert git(source, "rev-parse", "HEAD").decode().strip() == PIN, "Unexpected source revision"
assert git(source, "status", "--porcelain") == b"", "Source checkout is not clean"
tracked = git(source, "ls-files", "-z").decode("utf-8").split("\0")[:-1]
ts = [p for p in tracked if p.startswith("src/") and p.endswith((".ts", ".tsx"))]
tests = [p for p in ts if "/__tests__/" in p or ".test." in p or ".spec." in p]
code = [p for p in ts if p not in set(tests)]
hooks = [p for p in code if p.startswith("src/agent/hooks/")]
entries = []
for identifier, rel, needle in SOURCES:
entry = {"id": identifier, **digest(source, rel)}
lines = (source / rel).read_text(encoding="utf-8").splitlines()
matches = [i + 1 for i, line in enumerate(lines) if needle in line] if needle else [1]
assert matches, f"Anchor not found: {identifier} {rel} {needle}"
entry.update(anchorLine=matches[0], anchorNeedle=needle,
url=f"{URL}/blob/{PIN}/{rel}#L{matches[0]}",
gitBlob=git(source, "rev-parse", f"HEAD:{rel}").decode().strip())
entries.append(entry)
result = {
"schemaVersion": 1, "repository": URL + ".git", "commit": PIN,
"commitInfo": git(source, "show", "-s", "--format=%cI%n%s", "HEAD").decode().splitlines(),
"packageVersion": json.loads((source / "package.json").read_text(encoding="utf-8"))["version"],
"codeLicense": "Apache-2.0",
"documentExceptions": ["docs/CVM运行时对Agent模型的实证影响.md", "docs/reference/cvm-cognitive-runtime.md"],
"documentExceptionLicense": "CC-BY-NC-ND-4.0; linked and license-recorded only; not reproduced or adapted",
"publicTree": {name: any(p.startswith(name + "/") for p in tracked) for name in ["desktop", "src/pro", "vscode-extension", "src/tools/computer-use"]},
"inventory": {"trackedFiles": len(tracked), "srcTsTsxFiles": len(ts), "testFilesByPathOrName": len(tests),
"sourceFilesByExclusion": len(code), "sourceLinesSplitlines": sum(digest(source, p)["lines"] for p in code),
"hookSourceFiles": len(hooks)},
"inventoryMethod": "git ls-files; src/ .ts/.tsx; tests are /__tests__/ or .test. or .spec.; UTF-8 splitlines counts; no tests executed",
"sourceFiles": entries,
"productBaselineCommit": git(product, "rev-parse", PRODUCT_PIN).decode().strip(),
"productFiles": [digest(product, p) for p in PRODUCT],
"executionScope": {"fullApplicationStarted": False, "thirdPartyDependenciesInstalled": False, "modelRequests": 0,
"pureProbeOnly": "Five reviewed modules; separate original output and driver are sealed alongside this index"},
}
args.output.parent.mkdir(parents=True, exist_ok=True)
with args.output.open("x", encoding="utf-8", newline="\n") as stream:
json.dump(result, stream, ensure_ascii=False, indent=2)
stream.write("\n")
print(json.dumps({"commit": PIN, "inventory": result["inventory"], "indexedSources": len(entries), "productFiles": len(PRODUCT)}, ensure_ascii=False))
if __name__ == "__main__":
main()
@@ -0,0 +1,19 @@
import fs from 'node:fs';
import { chromium } from 'playwright';
const url = process.env.AGENT_WORKBENCH_URL || 'http://127.0.0.1:4319';
fs.mkdirSync('.qa/screenshots', { recursive: true });
const browser = await chromium.launch({ channel: 'msedge', headless: true });
try {
const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, deviceScaleFactor: 1 });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.goto(url, { waitUntil: 'domcontentloaded' });
await page.waitForLoadState('networkidle', { timeout: 6000 }).catch(() => {});
await page.locator('.connection.connected').waitFor({ timeout: 8000 });
await page.screenshot({ path: '.qa/screenshots/initial-desktop.png', fullPage: true });
fs.writeFileSync('.qa/initial-dom.html', await page.content());
console.log(JSON.stringify({ url, errors, buttons: await page.getByRole('button').allTextContents(),
labeledButtons: await page.locator('button[aria-label]').evaluateAll(nodes => nodes.map(node => node.getAttribute('aria-label'))),
text: (await page.locator('body').innerText()).slice(0, 3500) }, null, 2));
} finally { await browser.close(); }
@@ -0,0 +1,49 @@
// Legacy model fields describe the dispatched route, not authenticated model weights.
// Public execution views may contain only the most recent Runs; gaps stay explicit.
export function observedTaskModels(state,taskId=state?.execution?.task?.id){
const execution=state?.execution??{},runs=new Map(),attempts=new Map(),issues=[];
for(const run of [...(execution.runs??[]),execution.run].filter(Boolean)){
if(taskId&&run.taskId===taskId&&typeof run.id==='string')runs.set(run.id,run);
}
const task=execution.task?.id===taskId?execution.task:null;
const validCount=value=>Number.isSafeInteger(value)&&value>=0;
let declared=task&&validCount(task.usage?.requests)?task.usage.requests:null;
if(declared===null&&runs.size&&[...runs.values()].every(run=>validCount(run.usage?.requests)))
declared=[...runs.values()].reduce((total,run)=>total+run.usage.requests,0);
for(const run of runs.values())for(const receipt of run.consumption??[]){
if(typeof receipt.attemptId!=='string'||!receipt.attemptId){issues.push({kind:'missing_attempt_id',runId:run.id});continue;}
const attempt={runId:run.id,attemptId:receipt.attemptId,requestId:receipt.requestId??null,
model:typeof receipt.model==='string'&&receipt.model.trim()?receipt.model:null,
protocol:typeof receipt.protocol==='string'&&receipt.protocol.trim()?receipt.protocol:null,
connectionId:receipt.connectionId??null,outcome:receipt.outcome??null,
requestedModel:receipt.modelIdentity?.requestedModel??receipt.model??null,
modelIdentity:receipt.modelIdentity?structuredClone(receipt.modelIdentity):null,
usageStatus:receipt.usageStatus??'unknown',usage:receipt.usage??null};
const previous=attempts.get(attempt.attemptId);
if(previous){
if(JSON.stringify(previous)!==JSON.stringify(attempt))issues.push({kind:'conflicting_attempt',attemptId:attempt.attemptId,runIds:[previous.runId,run.id]});
continue;
}
attempts.set(attempt.attemptId,attempt);
if(!attempt.model||!attempt.protocol)issues.push({kind:'missing_route_identity',attemptId:attempt.attemptId});
if(attempt.usageStatus==='reported'&&!attempt.usage)issues.push({kind:'missing_reported_usage',attemptId:attempt.attemptId});
}
const observed=[...attempts.values()],models=[...new Set(observed.map(value=>value.model).filter(Boolean))],routes=new Map();
for(const attempt of observed){
const identity={connectionId:attempt.connectionId,model:attempt.model,protocol:attempt.protocol},key=JSON.stringify(identity);
if(!routes.has(key))routes.set(key,{...identity,requests:0,reportedUsageRequests:0,unknownUsageRequests:0});
const route=routes.get(key);route.requests++;
if(attempt.usageStatus==='reported'&&attempt.usage)route.reportedUsageRequests++;else route.unknownUsageRequests++;
}
if(!taskId)issues.push({kind:'missing_task_identity'});
if(declared!==null&&declared!==observed.length)issues.push({kind:'request_coverage_gap',recordedRequests:declared,observedAttempts:observed.length});
const status=issues.length?'incomplete':!observed.length?declared===0?'not_observed':'unavailable':models.length>1?'mixed':'observed';
const identities=observed.map(attempt=>attempt.modelIdentity),identityCounts={};
for(const identity of identities){const key=identity?.status??'historical_unchecked';identityCounts[key]=(identityCounts[key]??0)+1;}
return {schemaVersion:1,source:'task_run_consumption',taskId:taskId??null,status,
identityScope:'request_routes_and_upstream_reported_identifiers_not_model_weights',
responseIdentity:{counts:identityCounts,reportedModels:[...new Set(identities.flatMap(value=>value?.reportedModels??[]))],
allAccepted:observed.length>0&&issues.length===0&&identities.every(value=>value?.complete===true&&['matched','mapped'].includes(value.status))},
model:['observed','mixed'].includes(status)&&models.length===1?models[0]:null,models,
observedAttempts:observed.length,recordedRequests:declared,routes:[...routes.values()],attempts:observed,issues};
}
@@ -0,0 +1,46 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { chromium } from 'playwright';
import { until } from '../tests/helpers.mjs';
// Independent acceptance of the built app; this helper never supplies source fixes.
export async function verifyLiveReactClient(projectRoot, outputDirectory) {
const dist = fs.realpathSync.native(path.join(projectRoot, 'dist')), pageErrors = [], requestFailures = [], screenshots = [];
const server = http.createServer((request, response) => {
try {
const pathname = decodeURIComponent(new URL(request.url, 'http://127.0.0.1').pathname);
const candidate = path.resolve(dist, '.' + (pathname === '/' ? '/index.html' : pathname));
if (!candidate.startsWith(dist + path.sep) || !fs.existsSync(candidate) || !fs.statSync(candidate).isFile()
|| !fs.realpathSync.native(candidate).startsWith(dist + path.sep)) { response.writeHead(404); response.end(); return; }
const mime = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8' }[path.extname(candidate)] ?? 'application/octet-stream';
response.writeHead(200, { 'Content-Type': mime, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }); response.end(fs.readFileSync(candidate));
} catch { response.writeHead(400); response.end(); }
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1280, height: 920 } });
page.on('pageerror', error => pageErrors.push(error.message)); page.on('requestfailed', request => requestFailures.push(request.url() + ': ' + request.failure()?.errorText));
const count = async expected => { await until(async () => await page.locator('article').count() === expected); };
const text = async (locator, expected) => { await until(async () => (await locator.innerText()) === expected); };
fs.mkdirSync(outputDirectory, { recursive: true });
try {
await page.goto('http://127.0.0.1:' + server.address().port); await page.waitForLoadState('networkidle'); await count(3);
await page.getByLabel('任务状态').selectOption('pending'); await count(2);
await page.getByLabel('任务状态').selectOption('done'); await count(1);
await page.getByLabel('任务搜索').fill(' 不存在 '); await count(0); await page.getByText('没有匹配的任务', { exact: true }).waitFor({ state: 'visible' });
await page.getByLabel('任务搜索').fill(' 验证 '); await count(1);
await page.getByLabel('任务搜索').fill(''); await page.getByLabel('任务状态').selectOption('all'); await count(3);
await page.locator('article[data-task="api"]').getByRole('button', { name: '标为完成', exact: true }).click();
await text(page.locator('article[data-task="api"] .tag'), '已完成'); await text(page.locator('article[data-task="tests"] .tag'), '待完成');
await text(page.getByLabel('项目统计').locator('div').filter({ hasText: '完成任务' }).locator('strong'), '2');
await text(page.getByLabel('项目统计').locator('div').filter({ hasText: '待办工时' }).locator('strong'), '5小时');
const desktop = path.join(outputDirectory, 'live-react-desktop.png'); await page.screenshot({ path: desktop, scale: 'css' }); screenshots.push(desktop);
await page.setViewportSize({ width: 390, height: 844 }); await page.getByLabel('任务状态').selectOption('pending'); await count(1);
assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= 390));
const mobile = path.join(outputDirectory, 'live-react-mobile.png'); await page.screenshot({ path: mobile, scale: 'css' }); screenshots.push(mobile);
assert.deepEqual(pageErrors, []); assert.deepEqual(requestFailures, []);
return { success: true, browser: browser.version(), pageErrors, requestFailures, screenshots,
verified: ['pending/done filters', 'trimmed search', 'empty state', 'one-task toggle', 'unfiltered statistics', '390px layout'] };
} finally { await browser.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
}
@@ -0,0 +1,91 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash, randomUUID } from 'node:crypto';
import { performance } from 'node:perf_hooks';
import { pathToFileURL } from 'node:url';
import { execFileSync } from 'node:child_process';
// Own deterministic inputs; no model connection, user project or tool execution.
const phase = process.argv[2] ?? 'baseline';
assert.ok(['baseline', 'comparison'].includes(phase));
const output = path.resolve('.qa', 'project-cache-' + phase + '-' + randomUUID());
fs.mkdirSync(output, { recursive: true });
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
let baselineIdentity = null, modulePath = path.resolve('src/core/context/project-index.mjs');
if (phase === 'baseline') {
const commit = '606b5ec72edb2f86864b6cb2dfa1fab3f9e1af1a', gitPath = 'src/core/context/project-index.mjs';
const original = execFileSync('git', ['show', commit + ':' + gitPath], { windowsHide: true, encoding: 'utf8' });
const inspector = pathToFileURL(path.resolve('src/core/project-inspector.mjs')).href, files = pathToFileURL(path.resolve('src/server/files.mjs')).href;
const adjusted = original.replace("'../project-inspector.mjs'", JSON.stringify(inspector)).replace("'../../server/files.mjs'", JSON.stringify(files));
assert.notEqual(adjusted, original); modulePath = path.join(output, 'original-index.mjs'); fs.writeFileSync(modulePath, adjusted);
baselineIdentity = { commit, gitPath, originalSha256: hash(original), adjustedSha256: hash(adjusted), changes: 'Only two import paths relocated to current unchanged default inspection/file interfaces. Original parsing/cache algorithm preserved.' };
}
const { ProjectIndex } = await import(pathToFileURL(modulePath).href);
const rows = [];
const originalRead = fs.readFileSync;
const originalOpen = fs.openSync, originalClose = fs.closeSync, handles = new Map();
fs.openSync = function (filename, ...args) { const handle = originalOpen.call(this, filename, ...args); handles.set(handle, filename); return handle; };
fs.closeSync = function (handle) { handles.delete(handle); return originalClose.call(this, handle); };
let currentRoot = null, reads = 0, bytes = 0;
fs.readFileSync = function (filename, ...args) {
const result = originalRead.call(this, filename, ...args);
const source = typeof filename === 'number' ? handles.get(filename) : filename;
if (typeof source === 'string' && currentRoot && path.resolve(source).startsWith(currentRoot + path.sep)) {
reads++; bytes += Buffer.byteLength(result);
}
return result;
};
try {
for (const language of ['node', 'react', 'python']) {
const root = path.join(output, language); fs.mkdirSync(root);
const inputs = [];
const write = (name, content) => { fs.writeFileSync(path.join(root, name), content); inputs.push({ path: name, sha256: hash(content), bytes: Buffer.byteLength(content) }); };
if (language !== 'python') write('package.json', JSON.stringify({ name: 'cache-measure-' + language, type: 'module' }) + '\n');
else write('pyproject.toml', '[project]\nname = "cache-measure-python"\nversion = "0.1.0"\n');
const extension = language === 'node' ? 'mjs' : language === 'react' ? 'tsx' : 'py';
for (let file = 0; file < 72; file++) {
const declarations = Array.from({ length: 36 }, (_, item) => language === 'python'
? `def calculate_${file}_${item}(value):\n return value + ${item}\n`
: language === 'react' ? `export const Component${file}_${item} = ({value}: {value: number}) => <button aria-label="查看 ${file}-${item}">{value + ${item}}</button>;\n`
: `export function calculate${file}_${item}(value) { const result = value + ${item}; return result; }\n`);
write('module-' + file + '.' + extension, declarations.join(''));
}
const project = { id: 'measure-' + language, root: fs.realpathSync.native(root), name: '固定' + language + '解析样本' };
const cacheDirectory = path.join(output, 'derived-' + language);
const create = () => new ProjectIndex(phase === 'comparison' ? { cacheDirectory } : {});
let indexer = create(), first;
const measure = async (name, indexer) => {
reads = 0; bytes = 0; currentRoot = project.root;
const started = performance.now(), index = await indexer.refresh(project), durationMs = performance.now() - started;
currentRoot = null;
const result = { language, case: name, durationMs, sourceReads: reads, sourceBytesRead: bytes, refresh: index.refresh,
cache: index.cache ?? null, sourceFingerprint: index.sourceFingerprint, indexFingerprint: index.indexFingerprint,
coverage: index.coverage };
rows.push(result);
assert.equal(index.coverage.snapshotComplete, true); assert.equal(index.coverage.unindexedFiles, 0);
console.log(language + '/' + name + ': ' + durationMs.toFixed(1) + 'ms, reads=' + reads + ', updated=' + index.refresh.updatedFiles + ', reused=' + index.refresh.reusedFiles);
return index;
};
first = await measure('cold', indexer);
for (let i = 0; i < 3; i++) {
const warm = await measure('warm-' + (i + 1), indexer);
assert.equal(warm.indexFingerprint, first.indexFingerprint);
}
const restarted = await measure('new-indexer', create());
assert.equal(restarted.indexFingerprint, first.indexFingerprint);
const target = path.join(root, 'module-0.' + extension), old = fs.statSync(target);
const content = originalRead(target, 'utf8'), changed = content.replace('value + 0', 'value + 9');
assert.notEqual(content, changed); assert.equal(Buffer.byteLength(content), Buffer.byteLength(changed));
fs.writeFileSync(target, changed); fs.utimesSync(target, old.atime, old.mtime);
const modified = await measure('same-size-mtime-change', indexer);
assert.notEqual(modified.sourceFingerprint, first.sourceFingerprint); assert.equal(modified.refresh.updatedFiles, 1);
fs.writeFileSync(path.join(output, language + '-inputs.json'), JSON.stringify({ project, inputs,
mutation: { path: path.basename(target), before: hash(content), after: hash(changed), preservedSize: true, restoredMtime: true } }, null, 2) + '\n');
}
} finally { fs.readFileSync = originalRead; fs.openSync = originalOpen; fs.closeSync = originalClose; }
const report = { success: true, phase, at: new Date().toISOString(), node: process.version,
baselineIdentity,
interpretation: 'Local derived parsing only. Source reads include declarations and all current hashes. No model calls or token/cost inference.', rows };
fs.writeFileSync(path.join(output, 'result.json'), JSON.stringify(report, null, 2) + '\n');
console.log('EVIDENCE ' + output);
@@ -0,0 +1,140 @@
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { planReaBundle, copyReaBundle } from './bundle-rea.mjs';
import { planBrowserBundle, copyBrowserBundle } from './bundle-browser.mjs';
import { planDesktopBundle, buildNativeLauncher, copyDesktopBundle } from './bundle-desktop.mjs';
import { buildWindowsInstaller } from './build-installer.mjs';
import { createDocumentationBundle } from './documentation-bundle.mjs';
import { archiveWindowsDirectory } from './release-archive.mjs';
const args = process.argv.slice(2);
if (args.some(value => !['--help', '--immutable'].includes(value))) throw new Error('Unsupported argument; use --help.');
if (args.includes('--help')) { console.log('node scripts/package.mjs [--immutable] - create new portable/source releases and archives; existing release folders are never refreshed.'); process.exit(0); }
const root = process.cwd();
if (execFileSync('git', ['status', '--porcelain', '--untracked-files=all'], { cwd: root, encoding: 'utf8', windowsHide: true }).trim()) throw new Error('Commit the reviewed release inputs before packaging; sourceCommit must identify the actual shipped sources.');
const meta = JSON.parse(fs.readFileSync('package.json', 'utf8'));
const lock = JSON.parse(fs.readFileSync('package-lock.json', 'utf8'));
const reaPlan = planReaBundle(root);
const browserPlan = planBrowserBundle(root);
const desktopPlan = planDesktopBundle(root);
const releases = path.resolve(root, 'releases');
fs.mkdirSync(releases, { recursive: true });
const baseName = 'Agent-Workbench-' + meta.version;
const buildSuffix = args.includes('--immutable') || fs.existsSync(path.join(releases, baseName + '-win-x64')) ? '-' + new Date().toISOString().replace(/[-:TZ.]/g, '') : '';
const portableRoot = path.join(releases, baseName + '-win-x64' + buildSuffix);
const sourceRoot = path.join(releases, baseName + '-source' + buildSuffix);
const evidenceRoot = path.join(releases, baseName + '-evidence' + buildSuffix);
for (const target of [portableRoot, sourceRoot]) {
if (!path.resolve(target).startsWith(releases + path.sep) || fs.existsSync(target)) throw new Error('Release output must be a new folder under releases.');
fs.mkdirSync(target, { recursive: true });
}
const portableFiles = ['dist-client', 'dist-server', 'dist-desktop', 'public', 'examples', 'benchmarks', 'research', 'CHANGELOG.md', 'DESIGN.md', 'AGENTS.md', 'Start-Workbench.cmd', 'Stop-Workbench.cmd', 'Start-Desktop.cmd'];
const sourceFiles = ['src', 'public', 'scripts', 'tests', 'docs', 'examples', 'benchmarks', 'research', 'package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'index.html', 'mobile.html', '.gitignore', '.gitattributes', 'README.md', 'CHANGELOG.md', 'DESIGN.md', 'AGENTS.md', 'task_plan.md', 'findings.md', 'progress.md', 'Start-Workbench.cmd', 'Stop-Workbench.cmd', 'Start-Desktop.cmd'];
const copyTree = (source, destination) => fs.cpSync(source, destination, { recursive: true, filter: (from, to) => {
if (!fs.statSync(from).isFile() || !fs.existsSync(to)) return true;
return !fs.readFileSync(from).equals(fs.readFileSync(to));
} });
for (const name of portableFiles) copyTree(path.join(root, name), path.join(portableRoot, name));
fs.mkdirSync(path.join(portableRoot, 'scripts'), { recursive: true });
for (const name of ['Start-Workbench.ps1', 'Stop-Workbench.ps1', 'Start-Desktop.ps1', 'upgrade-running.mjs', 'python-check-runner.py']) fs.copyFileSync(path.join(root, 'scripts', name), path.join(portableRoot, 'scripts', name));
for (const name of sourceFiles) copyTree(path.join(root, name), path.join(sourceRoot, name));
const sourceCommit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', windowsHide: true }).trim();
const documentation = createDocumentationBundle({ root, portableRoot, evidenceRoot, archiveName: path.basename(evidenceRoot) + '.zip', sourceCommit });
const preferredNode = path.resolve(root, '..', 'tools', 'node-v24.22.1-win-x64', 'node.exe');
const nodeBinary = process.env.AGENT_WORKBENCH_NODE_PATH || (fs.existsSync(preferredNode) ? preferredNode : process.execPath);
const nodeLicense = path.join(path.dirname(nodeBinary), 'LICENSE');
if (!fs.existsSync(nodeLicense)) throw new Error('The bundled Node runtime requires its complete LICENSE next to node.exe.');
const nodeVersion = execFileSync(nodeBinary, ['--version'], { encoding: 'utf8', windowsHide: true }).trim();
if (!/^v24\./.test(nodeVersion)) throw new Error('This package was validated with Node 24.');
fs.mkdirSync(path.join(portableRoot, 'runtime'), { recursive: true });
const runtimeDestination = path.join(portableRoot, 'runtime', 'node.exe');
const digest = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
if (!fs.existsSync(runtimeDestination) || digest(runtimeDestination) !== digest(nodeBinary)) fs.copyFileSync(nodeBinary, runtimeDestination);
const npmRoot = path.join(path.dirname(nodeBinary), 'node_modules', 'npm');
if (!fs.existsSync(path.join(npmRoot, 'bin', 'npm-cli.js'))) throw new Error('The portable engineering runner requires the npm shipped with this Node distribution.');
copyTree(npmRoot, path.join(portableRoot, 'runtime', 'node_modules', 'npm'));
fs.copyFileSync(nodeLicense, path.join(portableRoot, 'runtime', 'LICENSE'));
fs.mkdirSync(path.join(sourceRoot, 'runtime'), { recursive: true });
fs.copyFileSync(nodeBinary, path.join(sourceRoot, 'runtime', 'node.exe'));
fs.copyFileSync(nodeLicense, path.join(sourceRoot, 'runtime', 'LICENSE'));
copyTree(npmRoot, path.join(sourceRoot, 'runtime', 'node_modules', 'npm'));
const launcherPath = path.join(root, '.qa', 'native-launcher', 'AgentWorkbench.exe');
const nativeLauncher = buildNativeLauncher(root, launcherPath);
const desktopRuntime = copyDesktopBundle(root, portableRoot, desktopPlan, { launcher: launcherPath });
copyDesktopBundle(root, sourceRoot, desktopPlan, { source: true });
const reaRuntime = copyReaBundle(path.join(portableRoot, 'runtime'), reaPlan);
copyReaBundle(path.join(sourceRoot, 'runtime'), reaPlan);
const browserRuntime = copyBrowserBundle(path.join(portableRoot, 'runtime'), browserPlan);
copyBrowserBundle(path.join(sourceRoot, 'runtime'), browserPlan);
const notices = ['Agent Workbench third-party notices', '',
'Original product code is supplied for the project owner. Its redistribution terms are determined by the project owner.',
'Third-party components remain governed by their own licenses. Full available license texts are reproduced below and in licenses/.', '',
'The release does not contain Claude Code or Cursor client binaries or recovered application source.', ''];
const licenseRoot = path.join(root, 'licenses'); fs.mkdirSync(licenseRoot, { recursive: true });
let licenseCount = 0;
for (const [location, entry] of Object.entries(lock.packages).sort(([a], [b]) => a.localeCompare(b))) {
if (!location.startsWith('node_modules/')) continue;
const packageRoot = path.resolve(root, location);
if (!packageRoot.startsWith(path.join(root, 'node_modules') + path.sep) || !fs.existsSync(packageRoot)) continue;
const pkg = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
const files = fs.readdirSync(packageRoot).filter(name => /^(licen[cs]e|copying)([.-].*)?$/i.test(name) && fs.statSync(path.join(packageRoot, name)).isFile());
notices.push('='.repeat(72), (pkg.name || location) + ' ' + (pkg.version || entry.version),
'License: ' + (typeof pkg.license === 'object' ? JSON.stringify(pkg.license) : pkg.license || entry.license || 'see upstream package'),
'Source package: ' + location, '');
if (!files.length) notices.push('License metadata is recorded above; associated parent package license text is included where supplied.', '');
for (const file of files) {
const text = fs.readFileSync(path.join(packageRoot, file), 'utf8');
notices.push(file, '', text, '');
fs.writeFileSync(path.join(licenseRoot, (pkg.name + '-' + pkg.version + '-' + file).replace(/[^a-z0-9_.-]/gi, '_') + '.txt'), text);
licenseCount++;
}
}
const nodeLicenseText = fs.readFileSync(nodeLicense, 'utf8');
const reaLicenseText = fs.readFileSync(path.join(reaPlan.installation.packageRoot, 'LICENSE'), 'utf8');
fs.writeFileSync(path.join(licenseRoot, 'REA-' + reaRuntime.version + '-LICENSE.txt'), reaLicenseText);
notices.push('='.repeat(72), 'REA (rea-agents) ' + reaRuntime.version, 'License: MIT', 'Source: https://github.com/morluto/rea', '', reaLicenseText,
'The fixed production dependency declarations, integrity metadata and file hashes are recorded in runtime/REA-RUNTIME.json.',
'Original package and dependency license texts remain under runtime/node_modules/. REA additional notices are retained at runtime/node_modules/rea-agents/THIRD_PARTY_NOTICES.md.', '');
fs.writeFileSync(path.join(licenseRoot, 'Node-' + nodeVersion + '-LICENSE.txt'), nodeLicenseText);
notices.push('='.repeat(72), 'Node.js ' + nodeVersion, '', nodeLicenseText);
notices.push('='.repeat(72), 'npm bundled with Node.js', 'Complete package and dependency licenses are retained under runtime/node_modules/npm/.', '', fs.readFileSync(path.join(npmRoot, 'LICENSE'), 'utf8'));
fs.writeFileSync(path.join(root, 'THIRD_PARTY_NOTICES.txt'), notices.join('\n'));
for (const output of [portableRoot, sourceRoot]) {
fs.cpSync(licenseRoot, path.join(output, 'licenses'), { recursive: true });
fs.copyFileSync(path.join(root, 'THIRD_PARTY_NOTICES.txt'), path.join(output, 'THIRD_PARTY_NOTICES.txt'));
}
function filesIn(directory, relative = '') {
return fs.readdirSync(path.join(directory, relative), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap(entry => {
const file = path.join(relative, entry.name);
return entry.isDirectory() ? filesIn(directory, file) : [file];
});
}
function manifest(directory, kind) {
const files = filesIn(directory).filter(file => file !== 'MANIFEST.json').map(file => {
const bytes = fs.readFileSync(path.join(directory, file));
return { path: file.replaceAll('\\', '/'), bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
});
const result = { app: 'agent-workbench', version: meta.version, kind, platform: 'win32-x64', nodeVersion,
createdAt: new Date().toISOString(), files };
fs.writeFileSync(path.join(directory, 'MANIFEST.json'), JSON.stringify(result, null, 2));
return result;
}
const portableManifest = manifest(portableRoot, 'portable');
manifest(sourceRoot, 'source');
const installer = buildWindowsInstaller({ root, portableRoot, outputRoot: releases });
function archive(directory) {
const destination = directory + '.zip';
if (!destination.startsWith(releases + path.sep)) throw new Error('Archive path is outside releases.');
archiveWindowsDirectory(directory, destination);
return { path: destination, bytes: fs.statSync(destination).size, sha256: createHash('sha256').update(fs.readFileSync(destination)).digest('hex') };
}
const result = { portableRoot, sourceRoot, evidenceRoot, portable: archive(portableRoot), source: archive(sourceRoot), evidence: archive(evidenceRoot), documentation: { sourceCommit, originalFiles: documentation.originalFiles, originalBytes: documentation.originalBytes, shippedFiles: documentation.shipped.length, shippedBytes: documentation.shipped.reduce((sum, row) => sum + row.bytes, 0), evidenceManifestSha256: documentation.evidenceManifestSha256 }, installer, desktopRuntime, nativeLauncher, nodeVersion, reaRuntime, portableFiles: portableManifest.files.length, licenseTexts: licenseCount + 2 };
result.browserRuntime = { playwrightVersion: browserRuntime.playwrightVersion, packages: browserRuntime.packages.map(pkg => ({ name: pkg.name, version: pkg.version, files: pkg.files.length })) };
fs.writeFileSync(path.join(releases, 'latest.json'), JSON.stringify(result, null, 2));
console.log(JSON.stringify(result, null, 2));
@@ -0,0 +1,223 @@
"""Collect actual Workbench Python checks after their execution is approved."""
import hashlib
import json
import os
from pathlib import Path
import sys
import traceback
sys.dont_write_bytecode = True
def sha(data):
return hashlib.sha256(data).hexdigest()
def checked_path(root, relative):
if not isinstance(relative, str) or not relative or "\0" in relative:
raise ValueError("Invalid planned Python path")
candidate = (root / relative).resolve(strict=True)
if not candidate.is_relative_to(root):
raise ValueError("Python input is outside the sealed project")
return candidate
def verify_sources(root, files):
for item in files:
filename = checked_path(root, item["path"])
if not filename.is_file() or sha(filename.read_bytes()) != item["sha256"]:
raise ValueError("Planned Python source changed: " + item["path"])
def compile_sources(root, files):
failures = []
for item in files:
filename = checked_path(root, item["path"])
data = filename.read_bytes()
try:
compile(data, str(filename), "exec", dont_inherit=True)
except (SyntaxError, ValueError) as error:
failures.append({"path": item["path"], "message": str(error), "line": getattr(error, "lineno", None)})
traceback.print_exception(type(error), error, error.__traceback__)
print("Python source compilation: %d / %d" % (len(files) - len(failures), len(files)))
return {"compilation": {"compiled": len(files) - len(failures), "total": len(files), "failures": failures}}, 1 if failures else 0
def count_records(records):
states = [item["status"] for item in records]
return {"total": len(states), "passed": states.count("passed"), "failed": states.count("failed"),
"skipped": states.count("skipped"), "cancelled": states.count("pending")}
def unittest_sources(root, settings):
import unittest
class CollectedResult(unittest.TextTestResult):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.records = []
self.active = {}
self.collection_errors = 0
self.collection_skipped = 0
def startTest(self, test):
super().startTest(test)
# Test.id() is a display name. Repeated cases and subtests belong
# to their actual startTest execution ordinal, not that name.
self.active[id(test)] = len(self.records)
self.records.append({"status": "pending"})
def stopTest(self, test):
self.active.pop(id(test), None)
super().stopTest(test)
def mark(self, test, status):
index = self.active.get(id(test))
if index is None:
index = self.active.get(id(getattr(test, "test_case", None)))
if index is None:
if status == "failed":
self.collection_errors += 1
elif status == "skipped":
self.collection_skipped += 1
return
record = self.records[index]
if record["status"] != "failed" and (record["status"] != "skipped" or status == "failed"):
record["status"] = status
def addSuccess(self, test):
self.mark(test, "passed")
super().addSuccess(test)
def addFailure(self, test, error):
self.mark(test, "failed")
super().addFailure(test, error)
def addError(self, test, error):
self.mark(test, "failed")
super().addError(test, error)
def addSkip(self, test, reason):
self.mark(test, "skipped")
super().addSkip(test, reason)
def addExpectedFailure(self, test, error):
self.mark(test, "skipped")
super().addExpectedFailure(test, error)
def addUnexpectedSuccess(self, test):
self.mark(test, "failed")
super().addUnexpectedSuccess(test)
def addSubTest(self, test, subtest, error):
if error is not None:
self.mark(test, "failed")
super().addSubTest(test, subtest, error)
start = checked_path(root, settings["startDirectory"])
if not start.is_dir():
raise ValueError("Unittest discovery needs a project directory")
sys.path[:0] = [str(root), str(root / "src")]
loader = unittest.TestLoader()
suite = loader.discover(str(start), pattern=settings["pattern"])
result = unittest.TextTestRunner(verbosity=2, resultclass=CollectedResult).run(suite)
if result.testsRun != len(result.records):
raise ValueError("Unittest execution count was not collected consistently")
return {"tests": count_records(result.records), "framework": "unittest", "frameworkVersion": sys.version.split()[0],
"collectionErrors": result.collection_errors, "collectionSkipped": result.collection_skipped}, 0 if result.wasSuccessful() else 1
def pytest_sources(root, settings):
# Import the host framework before adding project imports. Autoloaded
# environment plugins and addopts are excluded by the host check contract.
import pytest
sys.path[:0] = [str(root), str(root / "src")]
class Collector:
def __init__(self):
self.records = []
self.ordinals = {}
self.active = None
self.collection_errors = 0
self.collection_skipped = 0
def pytest_collection_finish(self, session):
self.records = [{"status": "pending", "nodeid": item.nodeid} for item in session.items]
self.ordinals = {}
for index, item in enumerate(session.items):
self.ordinals.setdefault(id(item), []).append(index)
def pytest_collectreport(self, report):
if report.failed:
self.collection_errors += 1
elif report.skipped:
self.collection_skipped += 1
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_protocol(self, item, nextitem):
pending = self.ordinals.get(id(item), [])
self.active = pending.pop(0) if pending else None
try:
yield
finally:
self.active = None
def pytest_runtest_logreport(self, report):
if self.active is None or self.records[self.active]["nodeid"] != report.nodeid:
self.collection_errors += 1
return
record = self.records[self.active]
if report.failed:
record["status"] = "failed"
elif record["status"] != "failed" and (report.skipped or hasattr(report, "wasxfail")):
record["status"] = "skipped"
elif record["status"] == "pending" and report.when == "call" and report.passed:
record["status"] = "passed"
collector = Collector()
args = [str(checked_path(root, relative)) for relative in settings["testPaths"]]
args += ["-p", "no:cacheprovider", "--import-mode=importlib", "-o", "addopts="]
if settings.get("configPath"):
args += ["-c", str(checked_path(root, settings["configPath"]))]
code = int(pytest.main(args, plugins=[collector]))
return {"tests": count_records(collector.records), "framework": "pytest", "frameworkVersion": pytest.__version__,
"collectionErrors": collector.collection_errors, "collectionSkipped": collector.collection_skipped}, code
def main():
payload_bytes = sys.stdin.buffer.read()
payload = json.loads(payload_bytes)
result_path = Path(sys.argv[1]).resolve()
root = Path(payload["root"]).resolve(strict=True)
if not root.is_dir() or result_path.is_relative_to(root):
raise ValueError("Result collection must use the owned host directory")
executable = Path(os.path.realpath(sys.executable))
base_executable = Path(os.path.realpath(getattr(sys, "_base_executable", sys.executable)))
identity = {"schemaVersion": 1, "kind": "python-check-result", "invocationId": payload["invocationId"],
"inputSha256": sha(payload_bytes), "mode": payload["mode"], "runnerSha256": sha(Path(__file__).read_bytes()),
"runtime": {"executable": str(executable), "version": sys.version.split()[0], "sha256": sha(executable.read_bytes()),
"baseExecutable": str(base_executable), "baseSha256": sha(base_executable.read_bytes())}}
try:
verify_sources(root, payload["files"])
if payload["mode"] == "compile":
evidence, code = compile_sources(root, payload["files"])
elif payload["mode"] == "unittest":
evidence, code = unittest_sources(root, payload["settings"])
elif payload["mode"] == "pytest":
evidence, code = pytest_sources(root, payload["settings"])
else:
raise ValueError("Unknown built-in Python check")
output = {**identity, **evidence, "exitCode": code}
except BaseException as error:
traceback.print_exception(type(error), error, error.__traceback__)
output = {**identity, "exitCode": 1, "collectorError": type(error).__name__ + ": " + str(error)}
code = 1
temporary = result_path.with_suffix(".tmp")
with temporary.open("x", encoding="utf-8") as stream:
json.dump(output, stream, ensure_ascii=False)
temporary.replace(result_path)
return code
if __name__ == "__main__":
raise SystemExit(main())

Some files were not shown because too many files have changed in this diff Show More