docs: seal Messages release and rejected Claude identity preflight
@@ -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 @@
|
||||
{ "unfinished":
|
||||
@@ -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,30 @@
|
||||
{
|
||||
"_approval-presentation-Chut4EFA.js": {
|
||||
"file": "assets/approval-presentation-Chut4EFA.js",
|
||||
"name": "approval-presentation"
|
||||
},
|
||||
"index.html": {
|
||||
"file": "assets/desktop-BVDBowt7.js",
|
||||
"name": "desktop",
|
||||
"src": "index.html",
|
||||
"isEntry": true,
|
||||
"imports": [
|
||||
"_approval-presentation-Chut4EFA.js"
|
||||
],
|
||||
"css": [
|
||||
"assets/desktop-D67Tn6c_.css"
|
||||
]
|
||||
},
|
||||
"mobile.html": {
|
||||
"file": "assets/mobile-4zqcwTeD.js",
|
||||
"name": "mobile",
|
||||
"src": "mobile.html",
|
||||
"isEntry": true,
|
||||
"imports": [
|
||||
"_approval-presentation-Chut4EFA.js"
|
||||
],
|
||||
"css": [
|
||||
"assets/mobile-joLHctQw.css"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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,8 @@
|
||||
<!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> <script type="module" crossorigin src="/assets/desktop-BVDBowt7.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/assets/approval-presentation-Chut4EFA.js">
|
||||
<link rel="stylesheet" crossorigin href="/assets/desktop-D67Tn6c_.css">
|
||||
</head>
|
||||
<body><div id="root"></div></body>
|
||||
</html>
|
||||
@@ -0,0 +1,5 @@
|
||||
[
|
||||
"/assets/approval-presentation-Chut4EFA.js",
|
||||
"/assets/mobile-4zqcwTeD.js",
|
||||
"/assets/mobile-joLHctQw.css"
|
||||
]
|
||||
@@ -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,12 @@
|
||||
const CACHE = 'workbench-mobile-e5ad586baebabce5b65a';
|
||||
const FILES = ["/","/mobile.webmanifest","/mobile-icon.svg","/mobile-touch-icon.png","/assets/approval-presentation-Chut4EFA.js","/assets/mobile-4zqcwTeD.js","/assets/mobile-joLHctQw.css"];
|
||||
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()));
|
||||
});
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -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, 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> <script type="module" crossorigin src="/assets/mobile-4zqcwTeD.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/assets/approval-presentation-Chut4EFA.js">
|
||||
<link rel="stylesheet" crossorigin href="/assets/mobile-joLHctQw.css">
|
||||
</head><body><div id="mobile-root"></div></body></html>
|
||||
@@ -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"}]}
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
|
||||
// src/desktop/preload.cjs
|
||||
var { contextBridge, ipcRenderer } = require("electron");
|
||||
contextBridge.exposeInMainWorld("desktopWorkbench", Object.freeze({
|
||||
protocol: "agent-workbench-desktop-v1",
|
||||
status: () => ipcRenderer.invoke("awb:desktop-status"),
|
||||
pickProject: () => ipcRenderer.invoke("awb:desktop-pick-project"),
|
||||
projectFolder: (projectId) => ipcRenderer.invoke("awb:desktop-project-folder", { projectId }),
|
||||
openFilePreview: (input) => ipcRenderer.invoke("awb:desktop-file-preview", input),
|
||||
reviewTask: (input) => ipcRenderer.invoke("awb:desktop-review-task", input),
|
||||
revealFile: (input) => ipcRenderer.invoke("awb:desktop-reveal-file", input),
|
||||
stopHost: () => ipcRenderer.invoke("awb:desktop-stop-host"),
|
||||
browsingLayout: (input) => ipcRenderer.invoke("awb:browsing-layout", input)
|
||||
}));
|
||||
@@ -0,0 +1,453 @@
|
||||
// src/desktop/host-cli.mjs
|
||||
import fs5 from "node:fs";
|
||||
import path6 from "node:path";
|
||||
import os from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
// src/core/desktop/host-controller.mjs
|
||||
import fs4 from "node:fs";
|
||||
import path5 from "node:path";
|
||||
import { spawn, execFileSync as execFileSync2 } from "node:child_process";
|
||||
import { randomBytes, randomUUID as randomUUID2 } from "node:crypto";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
|
||||
// src/shared/contracts/desktop-host.mjs
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
var HOST_PROTOCOL = "agent-workbench-host-v1";
|
||||
var HOST_REGISTRATION_FILE = "host-authority-v1.json";
|
||||
var hostError = (message, code = "HOST_IDENTITY_REJECTED", status = 409) => Object.assign(new Error(message), { code, status });
|
||||
var canonicalHost = (value) => Array.isArray(value) ? value.map(canonicalHost) : value && typeof value === "object" ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonicalHost(value[key])])) : value;
|
||||
function hostProof(identity, challenge, secret) {
|
||||
if (!/^[a-f0-9]{64}$/.test(challenge) || !Buffer.isBuffer(secret) || secret.length !== 32) throw hostError("\u5BBF\u4E3B\u6838\u9A8C\u6311\u6218\u683C\u5F0F\u65E0\u6548\u3002", "HOST_CHALLENGE_INVALID", 400);
|
||||
return createHmac("sha256", secret).update(JSON.stringify(canonicalHost({ identity, challenge }))).digest("hex");
|
||||
}
|
||||
function verifyHostProof(reply, challenge, secret) {
|
||||
if (!reply?.identity || reply.challenge !== challenge || !/^[a-f0-9]{64}$/.test(reply.proof ?? "")) throw hostError("\u5BBF\u4E3B\u6CA1\u6709\u63D0\u4F9B\u5339\u914D\u7684\u5B9E\u4F8B\u6838\u9A8C\u3002");
|
||||
const actual = Buffer.from(reply.proof, "hex"), expected = Buffer.from(hostProof(reply.identity, challenge, secret), "hex");
|
||||
if (!timingSafeEqual(actual, expected)) throw hostError("\u7AEF\u53E3\u54CD\u5E94\u4E0D\u5C5E\u4E8E\u767B\u8BB0\u7684\u6267\u884C\u5BBF\u4E3B\u3002");
|
||||
return reply.identity;
|
||||
}
|
||||
|
||||
// src/core/process-environment.mjs
|
||||
import path from "node:path";
|
||||
function projectEnvironment(extra = {}) {
|
||||
const allowed = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|homedrive|homepath|home|appdata|localappdata|programfiles(?:\(x86\))?|commonprogramfiles(?:\(x86\))?|lang|lc_all)$/i;
|
||||
const environment = Object.fromEntries(Object.entries(process.env).filter(([name]) => allowed.test(name)));
|
||||
const inheritedPath = Object.entries(environment).find(([name]) => name.toLowerCase() === "path")?.[1] || "";
|
||||
for (const name of Object.keys(environment)) if (name.toLowerCase() === "path") delete environment[name];
|
||||
return { ...environment, PATH: [path.dirname(process.execPath), inheritedPath].filter(Boolean).join(path.delimiter), ...extra };
|
||||
}
|
||||
|
||||
// src/core/desktop/process-identity.mjs
|
||||
import fs2 from "node:fs";
|
||||
import path3 from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
// src/core/desktop/file-state.mjs
|
||||
import fs from "node:fs";
|
||||
import path2 from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
var normalized = (value) => process.platform === "win32" ? value.toLowerCase() : value;
|
||||
var samePath = (a, b) => normalized(path2.resolve(a)) === normalized(path2.resolve(b));
|
||||
function assertLocalTree(absolute, { missing = false } = {}) {
|
||||
const resolved = path2.resolve(absolute), parsed = path2.parse(resolved);
|
||||
let current = parsed.root;
|
||||
const components = resolved.slice(parsed.root.length).split(path2.sep).filter(Boolean);
|
||||
for (const component of components) {
|
||||
if (component.includes(":") || component.includes("\0")) throw hostError("\u672C\u673A\u72B6\u6001\u8DEF\u5F84\u683C\u5F0F\u65E0\u6548\u3002");
|
||||
current = path2.join(current, component);
|
||||
let stat;
|
||||
try {
|
||||
stat = fs.lstatSync(current);
|
||||
} catch (cause) {
|
||||
if (missing && cause.code === "ENOENT") return resolved;
|
||||
throw cause;
|
||||
}
|
||||
if (stat.isSymbolicLink() || !samePath(current, fs.realpathSync.native(current))) throw hostError("\u672C\u673A\u72B6\u6001\u4E0D\u63A5\u53D7\u94FE\u63A5\u6216\u91CD\u89E3\u6790\u76EE\u5F55\u3002");
|
||||
if (stat.isFile() && stat.nlink !== 1) throw hostError("\u672C\u673A\u72B6\u6001\u6587\u4EF6\u5177\u6709\u591A\u4E2A\u8DEF\u5F84\u3002");
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
function ownedChild(root, relative, { missing = false } = {}) {
|
||||
if (typeof relative !== "string") throw hostError("\u672C\u673A\u72B6\u6001\u8DEF\u5F84\u65E0\u6548\u3002");
|
||||
assertLocalTree(root);
|
||||
const base = fs.realpathSync.native(root), target = path2.resolve(base, relative);
|
||||
if (path2.isAbsolute(relative) || path2.win32.isAbsolute(relative) || relative.includes("\0") || !normalized(target).startsWith(normalized(base + path2.sep))) throw hostError("\u672C\u673A\u72B6\u6001\u8DEF\u5F84\u8D85\u51FA\u6240\u5C5E\u76EE\u5F55\u3002");
|
||||
let existing = target;
|
||||
while (!fs.existsSync(existing)) {
|
||||
if (!missing) throw hostError("\u672C\u673A\u72B6\u6001\u6587\u4EF6\u4E0D\u5B58\u5728\u3002", "HOST_REGISTRATION_MISSING");
|
||||
const parent = path2.dirname(existing);
|
||||
if (parent === existing) throw hostError("\u672C\u673A\u72B6\u6001\u8DEF\u5F84\u65E0\u6CD5\u6838\u5BF9\u3002");
|
||||
existing = parent;
|
||||
}
|
||||
const real = fs.realpathSync.native(existing);
|
||||
if (!samePath(base, real) && !normalized(real).startsWith(normalized(base + path2.sep))) throw hostError("\u672C\u673A\u72B6\u6001\u94FE\u63A5\u8D85\u51FA\u6240\u5C5E\u76EE\u5F55\u3002");
|
||||
if (fs.lstatSync(existing).isSymbolicLink()) throw hostError("\u672C\u673A\u72B6\u6001\u4E0D\u63A5\u53D7\u94FE\u63A5\u6216\u91CD\u89E3\u6790\u76EE\u5F55\u3002");
|
||||
const stat = fs.statSync(existing);
|
||||
if (stat.isFile() && stat.nlink !== 1) throw hostError("\u672C\u673A\u72B6\u6001\u6587\u4EF6\u5177\u6709\u591A\u4E2A\u8DEF\u5F84\u3002");
|
||||
return assertLocalTree(target, { missing });
|
||||
}
|
||||
function readState(file, maximum = 4 * 1024 * 1024) {
|
||||
assertLocalTree(file);
|
||||
const stat = fs.lstatSync(file);
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > maximum) throw hostError("\u672C\u673A\u72B6\u6001\u6587\u4EF6\u683C\u5F0F\u6216\u4F5C\u7528\u8303\u56F4\u65E0\u6548\u3002");
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
|
||||
} catch {
|
||||
throw hostError("\u672C\u673A\u72B6\u6001\u6587\u4EF6\u635F\u574F\uFF0C\u8BF7\u6838\u5BF9\u539F\u8BB0\u5F55\u3002");
|
||||
}
|
||||
}
|
||||
function writeState(file, value) {
|
||||
assertLocalTree(file, { missing: true });
|
||||
const directory = path2.dirname(file), temporary = path2.join(directory, "." + path2.basename(file) + "-" + randomUUID() + ".tmp");
|
||||
if (fs.existsSync(file)) readState(file);
|
||||
try {
|
||||
const descriptor = fs.openSync(temporary, "wx", 384);
|
||||
try {
|
||||
fs.writeFileSync(descriptor, JSON.stringify(value, null, 2) + "\n");
|
||||
fs.fsyncSync(descriptor);
|
||||
} finally {
|
||||
fs.closeSync(descriptor);
|
||||
}
|
||||
assertLocalTree(file, { missing: true });
|
||||
fs.renameSync(temporary, file);
|
||||
} finally {
|
||||
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
|
||||
}
|
||||
}
|
||||
|
||||
// src/core/desktop/process-identity.mjs
|
||||
function windowsProcessObservationScript(pid) {
|
||||
if (!Number.isInteger(pid) || pid < 1 || pid > 2147483647) throw hostError("\u5BBF\u4E3BPID\u65E0\u6548\u3002");
|
||||
const query = 'Get-CimInstance Win32_Process -Filter "ProcessId=' + pid + '"';
|
||||
return "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';[Console]::OutputEncoding=New-Object System.Text.UTF8Encoding($false);$awbProcess=" + query + ';if($null -eq $awbProcess){Write-Output "null";exit 0};try{$awbOwner=Invoke-CimMethod -InputObject $awbProcess -MethodName GetOwnerSid;if($awbOwner.ReturnValue -ne 0 -or -not $awbOwner.Sid){throw "Owner identity unavailable"};}catch{$awbRemaining=' + query + ';if($null -eq $awbRemaining){Write-Output "null";exit 0};throw};[pscustomobject]@{pid=[int]$awbProcess.ProcessId;parentPid=[int]$awbProcess.ParentProcessId;createdAt=$awbProcess.CreationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");executable=$awbProcess.ExecutablePath;userSid=$awbOwner.Sid}|ConvertTo-Json -Compress';
|
||||
}
|
||||
function observeWindowsProcess(pid) {
|
||||
if (process.platform !== "win32") throw hostError("\u6B64\u684C\u9762\u5BBF\u4E3B\u6838\u9A8C\u9700\u8981Windows\u3002", "HOST_PLATFORM_UNSUPPORTED");
|
||||
const script = windowsProcessObservationScript(pid);
|
||||
try {
|
||||
const shell = path3.join(process.env.SystemRoot || "C:\\Windows", "System32/WindowsPowerShell/v1.0/powershell.exe");
|
||||
const output = execFileSync(
|
||||
shell,
|
||||
["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")],
|
||||
{ windowsHide: true, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], timeout: 15e3, maxBuffer: 65536, env: projectEnvironment() }
|
||||
);
|
||||
const value = JSON.parse(output.trim().replace(/^\uFEFF/, ""));
|
||||
if (value === null) return null;
|
||||
if (value.pid !== pid || !Number.isFinite(Date.parse(value.createdAt)) || !/^S-1-\d+(?:-\d+)+$/.test(value.userSid) || !value.executable || !fs2.existsSync(value.executable)) throw new Error("Invalid observation");
|
||||
return { ...value, executable: fs2.realpathSync.native(value.executable) };
|
||||
} catch {
|
||||
throw hostError("\u65E0\u6CD5\u6838\u5BF9Windows\u5BBF\u4E3B\u521B\u5EFA\u3001\u7528\u6237\u6216\u53EF\u6267\u884C\u8EAB\u4EFD\uFF1B\u4E0D\u4F1A\u590D\u7528\u6216\u505C\u6B62\u672A\u77E5\u8FDB\u7A0B\u3002", "HOST_PROCESS_UNVERIFIED");
|
||||
}
|
||||
}
|
||||
function binaryIdentity(file) {
|
||||
assertLocalTree(file);
|
||||
const absolute = fs2.realpathSync.native(file), stat = fs2.lstatSync(absolute);
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 256 * 1024 * 1024) throw hostError("\u5BBF\u4E3B\u53EF\u6267\u884C\u6587\u4EF6\u8EAB\u4EFD\u65E0\u6548\u3002");
|
||||
return { path: absolute, bytes: stat.size, sha256: createHash("sha256").update(fs2.readFileSync(absolute)).digest("hex") };
|
||||
}
|
||||
|
||||
// src/core/desktop/app-installation.mjs
|
||||
import fs3 from "node:fs";
|
||||
import path4 from "node:path";
|
||||
import { createHash as createHash2 } from "node:crypto";
|
||||
function inspectHostInstallation(directory, { full = false, onProgress = null } = {}) {
|
||||
assertLocalTree(directory);
|
||||
const root = fs3.realpathSync.native(path4.resolve(directory));
|
||||
if (!fs3.statSync(root).isDirectory()) throw hostError("\u5BBF\u4E3B\u5B89\u88C5\u76EE\u5F55\u65E0\u6548\u3002");
|
||||
const digest = (value) => createHash2("sha256").update(value).digest("hex");
|
||||
const manifestFile = path4.join(root, "MANIFEST.json"), manifest = fs3.existsSync(manifestFile) ? readState(manifestFile, 16 * 1024 * 1024) : null;
|
||||
if (manifest && (manifest.app !== "agent-workbench" || !Array.isArray(manifest.files) || manifest.files.length > 6e4)) throw hostError("\u5BBF\u4E3B\u53D1\u884C\u6E05\u5355\u65E0\u6548\u3002");
|
||||
const version = manifest?.version ?? (fs3.existsSync(path4.join(root, "package.json")) ? readState(path4.join(root, "package.json")).version : null);
|
||||
if (typeof version !== "string" || !/^\d+\.\d+\.\d+$/.test(version)) throw hostError("\u5BBF\u4E3B\u5B89\u88C5\u7248\u672C\u65E0\u6548\u3002");
|
||||
const files = /* @__PURE__ */ new Set(["dist-server/server.mjs", "dist-server/hot-upgrade.mjs", "dist-client/index.html"]);
|
||||
if (!manifest || fs3.existsSync(path4.join(root, "dist-server/host-launcher.mjs"))) files.add("dist-server/host-launcher.mjs");
|
||||
if (fs3.existsSync(path4.join(root, "dist-server/install-manager.mjs"))) files.add("dist-server/install-manager.mjs");
|
||||
for (const relative of ["dist-desktop/main.cjs", "dist-desktop/preload.cjs"]) if (fs3.existsSync(path4.join(root, relative))) files.add(relative);
|
||||
const names = /* @__PURE__ */ new Map();
|
||||
for (const row of manifest?.files ?? []) {
|
||||
if (!row || typeof row.path !== "string" || row.path.includes("\\") || row.path.split("/").includes("..") || names.has(row.path) || !/^[a-f0-9]{64}$/.test(row.sha256 ?? "") || !Number.isSafeInteger(row.bytes) || row.bytes < 0) throw hostError("\u5BBF\u4E3B\u6E05\u5355\u5305\u542B\u91CD\u590D\u6216\u8D8A\u754C\u8F93\u5165\u3002");
|
||||
names.set(row.path, row);
|
||||
if (full || /^(dist-client|dist-server|dist-desktop)\//.test(row.path)) files.add(row.path);
|
||||
}
|
||||
if (!manifest || manifest.kind === "source") for (const entry of fs3.readdirSync(path4.join(root, "dist-client/assets"))) files.add("dist-client/assets/" + entry);
|
||||
const selected = [...files].sort(), totalBytes = selected.reduce((sum, name) => sum + (names.get(name)?.bytes ?? 0), 0);
|
||||
let completedFiles = 0, completedBytes = 0;
|
||||
const report = (currentPath) => onProgress?.({ scope: full ? "full-manifest" : "loaded-inputs", root, totalFiles: selected.length, totalBytes: manifest ? totalBytes : null, completedFiles, completedBytes, currentPath });
|
||||
report(null);
|
||||
const inputs = selected.map((relative) => {
|
||||
const file = ownedChild(root, relative), identity = binaryIdentity(file), declared = names.get(relative);
|
||||
if (manifest?.kind === "portable" && !declared) throw hostError("\u5B9E\u9645\u5BBF\u4E3B\u7A0B\u5E8F\u4E0D\u5728\u539F\u53D1\u884C\u6E05\u5355\u4E2D\u3002");
|
||||
if (declared && (identity.bytes !== declared.bytes || identity.sha256 !== declared.sha256)) throw hostError("\u5B9E\u9645\u5BBF\u4E3B\u7A0B\u5E8F\u4E0E\u539F\u53D1\u884C\u6E05\u5355\u4E0D\u4E00\u81F4\u3002");
|
||||
completedFiles++;
|
||||
completedBytes += identity.bytes;
|
||||
report(relative);
|
||||
return { path: relative, bytes: identity.bytes, sha256: identity.sha256 };
|
||||
});
|
||||
const result = {
|
||||
root,
|
||||
version,
|
||||
kind: manifest?.kind ?? "development-build",
|
||||
manifestSha256: manifest ? digest(fs3.readFileSync(manifestFile)) : null,
|
||||
inputs,
|
||||
verification: full ? "full-manifest" : "loaded-host-and-client-inputs"
|
||||
};
|
||||
return { ...result, identitySha256: digest(JSON.stringify(canonicalHost(result))) };
|
||||
}
|
||||
|
||||
// src/core/desktop/host-controller.mjs
|
||||
var HOST_ENVIRONMENT = Object.freeze(["AGENT_WORKBENCH_DEEPSEEK_ROOT", "AGENT_WORKBENCH_PURGE_ROOT", "AGENT_WORKBENCH_PYTHON_PATH", "AGENT_WORKBENCH_TEST_PYTHON"]);
|
||||
async function jsonResponse(response) {
|
||||
if (!response.ok) throw hostError("\u672C\u673A\u5BBF\u4E3B\u63A5\u53E3\u62D2\u7EDD\u64CD\u4F5C\uFF08HTTP " + response.status + "\uFF09\u3002", "HOST_API_REJECTED", response.status);
|
||||
const chunks = [];
|
||||
let length = 0;
|
||||
for await (const chunk of response.body) {
|
||||
length += chunk.length;
|
||||
if (length > 4 * 1024 * 1024) throw hostError("\u672C\u673A\u5BBF\u4E3B\u54CD\u5E94\u8FC7\u5927\u3002");
|
||||
chunks.push(chunk);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
||||
} catch {
|
||||
throw hostError("\u7AEF\u53E3\u672A\u8FD4\u56DE\u6709\u6548\u7684\u5BBF\u4E3B\u534F\u8BAE\u3002");
|
||||
}
|
||||
}
|
||||
var HostController = class {
|
||||
constructor({ appRoot: appRoot2, dataRoot: dataRoot2, port = 4318, nodePath: nodePath2 = null, timeoutMs = 45e3, environment = {} }) {
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535 || typeof dataRoot2 !== "string" || !path5.isAbsolute(dataRoot2)) throw hostError("\u684C\u9762\u5BBF\u4E3B\u76EE\u5F55\u6216\u7AEF\u53E3\u65E0\u6548\u3002");
|
||||
this.installation = inspectHostInstallation(appRoot2);
|
||||
this.appRoot = this.installation.root;
|
||||
assertLocalTree(dataRoot2, { missing: true });
|
||||
fs4.mkdirSync(dataRoot2, { recursive: true });
|
||||
this.dataRoot = fs4.realpathSync.native(dataRoot2);
|
||||
const bundled = path5.join(this.appRoot, "runtime/node.exe");
|
||||
const executable = nodePath2 ?? (fs4.existsSync(bundled) ? bundled : !process.versions.electron ? process.execPath : null);
|
||||
if (!executable) throw hostError("\u684C\u9762\u5B89\u88C5\u7F3A\u5C11\u72EC\u7ACBNode\u5BBF\u4E3B\u3002");
|
||||
this.node = binaryIdentity(executable);
|
||||
const version = execFileSync2(this.node.path, ["--version"], { encoding: "utf8", windowsHide: true, timeout: 1e4, env: projectEnvironment() }).trim();
|
||||
if (!/^v24\./.test(version)) throw hostError("\u684C\u9762\u5BBF\u4E3B\u9700\u8981\u5DF2\u7ECF\u6838\u9A8C\u7684Node24\u8FD0\u884C\u5668\u3002");
|
||||
this.node.version = version;
|
||||
this.port = port;
|
||||
this.url = "http://127.0.0.1:" + port;
|
||||
this.timeoutMs = Math.min(6e4, Math.max(1e3, timeoutMs));
|
||||
const allowed = new Set(HOST_ENVIRONMENT);
|
||||
if (Object.keys(environment).some((key) => !allowed.has(key) || typeof environment[key] !== "string" || !path5.isAbsolute(environment[key]))) throw hostError("\u5BBF\u4E3B\u542F\u52A8\u53EA\u63A5\u53D7\u5DF2\u58F0\u660E\u7684\u672C\u673A\u8FD0\u884C\u5668\u8DEF\u5F84\u3002");
|
||||
this.environment = environment;
|
||||
}
|
||||
async api(route, { method = "GET", input = null, timeoutMs = 15e3 } = {}) {
|
||||
if (typeof route !== "string" || !route.startsWith("/") || route.startsWith("//")) throw hostError("\u5BBF\u4E3B\u63A5\u53E3\u8DEF\u5F84\u65E0\u6548\u3002");
|
||||
return jsonResponse(await fetch(this.url + "/api" + route, {
|
||||
method,
|
||||
headers: {
|
||||
Connection: "close",
|
||||
...this.token ? { "X-Workbench-Token": this.token } : {},
|
||||
...input ? { "Content-Type": "application/json" } : {}
|
||||
},
|
||||
body: input ? JSON.stringify(input) : void 0,
|
||||
signal: AbortSignal.timeout(timeoutMs)
|
||||
}));
|
||||
}
|
||||
async health() {
|
||||
try {
|
||||
return await this.api("/health", { timeoutMs: 1500 });
|
||||
} catch (cause) {
|
||||
if (cause.cause?.code === "ECONNREFUSED" || cause.cause?.errors?.every((value) => value.code === "ECONNREFUSED")) return null;
|
||||
throw hostError("\u7AEF\u53E3\u88AB\u5360\u7528\u6216\u54CD\u5E94\u65E0\u6CD5\u6838\u5BF9\uFF1B\u4E0D\u4F1A\u542F\u52A8\u53E6\u4E00\u5957\u5BBF\u4E3B\u3002", "HOST_PORT_UNVERIFIED");
|
||||
}
|
||||
}
|
||||
async connect() {
|
||||
const health = await this.health();
|
||||
if (!health) return null;
|
||||
if (health.app !== "agent-workbench" || health.ready !== true || !Number.isInteger(health.pid)) throw hostError("\u7AEF\u53E3\u5C5E\u4E8E\u672A\u77E5\u670D\u52A1\u3002");
|
||||
const bootstrap = await this.api("/bootstrap");
|
||||
if (bootstrap.version !== this.installation.version || typeof bootstrap.token !== "string") throw hostError("\u8FD0\u884C\u7248\u672C\u4E0D\u5339\u914D\uFF0C\u8BF7\u4F7F\u7528\u660E\u786E\u7684\u5347\u7EA7\u6D41\u7A0B\u3002", "HOST_VERSION_MISMATCH");
|
||||
this.token = bootstrap.token;
|
||||
const challenge = randomBytes(32).toString("hex"), reply = await this.api("/host/identity?challenge=" + challenge);
|
||||
ownedChild(this.dataRoot, ".secrets");
|
||||
const registration = readState(ownedChild(this.dataRoot, ".secrets/" + HOST_REGISTRATION_FILE), 16384);
|
||||
if (registration.schema !== 1 || registration.protocol !== HOST_PROTOCOL || !/^[A-Za-z0-9+/]{43}=$/.test(registration.secret ?? "")) throw hostError("\u672C\u673A\u539F\u6CE8\u518C\u683C\u5F0F\u65E0\u6CD5\u6838\u5BF9\u3002");
|
||||
const identity = verifyHostProof(reply, challenge, Buffer.from(registration.secret, "base64"));
|
||||
const actual = observeWindowsProcess(identity.pid), caller = observeWindowsProcess(process.pid);
|
||||
if (!actual || !caller || identity.pid !== health.pid || identity.pid !== registration.pid || identity.createdAt !== actual.createdAt || identity.createdAt !== registration.createdAt || identity.instanceId !== registration.instanceId || identity.ownerId !== registration.ownerId || identity.userSid !== actual.userSid || identity.userSid !== registration.userSid || identity.userSid !== caller.userSid || identity.protocol !== HOST_PROTOCOL || identity.version !== this.installation.version || identity.port !== this.port || !samePath(identity.dataRoot, this.dataRoot) || !samePath(identity.runtimeRoot, this.appRoot) || identity.runtimeIdentity !== this.installation.identitySha256 || !samePath(identity.executable.path, actual.executable) || identity.executable.sha256 !== this.node.sha256 || binaryIdentity(actual.executable).sha256 !== this.node.sha256) throw hostError("\u5B9E\u9645PID\u521B\u5EFA\u3001\u7528\u6237\u3001\u7A0B\u5E8F\u3001\u5B89\u88C5\u6216\u6570\u636E\u76EE\u5F55\u4E0E\u539F\u5BBF\u4E3B\u767B\u8BB0\u4E0D\u4E00\u81F4\u3002");
|
||||
const info = readState(ownedChild(this.dataRoot, "service-info.json"));
|
||||
if (info.pid !== identity.pid || info.instanceId !== identity.instanceId || info.createdAt !== identity.createdAt || info.port !== this.port || info.userSid !== identity.userSid || info.ownerId !== identity.ownerId || info.runtimeIdentity !== identity.runtimeIdentity || !samePath(info.appRoot, identity.appRoot) || !samePath(info.dataRoot, this.dataRoot) || !samePath(info.runtimeRoot, this.appRoot)) throw hostError("\u672C\u673A\u5BBF\u4E3B\u7D22\u5F15\u4E0E\u5B9E\u9645\u5B9E\u4F8B\u4E0D\u4E00\u81F4\u3002");
|
||||
this.identity = identity;
|
||||
return { url: this.url, identity };
|
||||
}
|
||||
async lock(action) {
|
||||
const lockDirectory = ownedChild(this.dataRoot, ".desktop-launch.lock", { missing: true }), nonce = randomUUID2(), observed = observeWindowsProcess(process.pid);
|
||||
const deadline = Date.now() + this.timeoutMs;
|
||||
while (true) {
|
||||
try {
|
||||
fs4.mkdirSync(lockDirectory, { mode: 448 });
|
||||
break;
|
||||
} catch (cause) {
|
||||
if (cause.code !== "EEXIST") throw cause;
|
||||
ownedChild(this.dataRoot, ".desktop-launch.lock");
|
||||
const ownerFile2 = path5.join(lockDirectory, "owner.json");
|
||||
if (fs4.existsSync(ownerFile2)) {
|
||||
ownedChild(this.dataRoot, ".desktop-launch.lock/owner.json");
|
||||
const owner = readState(ownerFile2, 16384);
|
||||
if (!Number.isInteger(owner.pid) || typeof owner.createdAt !== "string" || typeof owner.nonce !== "string") throw hostError("\u542F\u52A8\u9501\u7684\u539F\u8EAB\u4EFD\u65E0\u6CD5\u6838\u5BF9\u3002");
|
||||
const active = observeWindowsProcess(owner.pid);
|
||||
if (active && active.createdAt === owner.createdAt && (owner.userSid !== active.userSid || owner.userSid !== observed.userSid)) throw hostError("\u542F\u52A8\u9501\u4E0D\u5C5E\u4E8E\u5F53\u524DWindows\u7528\u6237\u3002");
|
||||
if (!active || active.createdAt !== owner.createdAt) {
|
||||
if (readState(ownerFile2).nonce !== owner.nonce) continue;
|
||||
const archive = ownedChild(this.dataRoot, ".desktop-launch-stale-" + randomUUID2(), { missing: true });
|
||||
try {
|
||||
fs4.renameSync(lockDirectory, archive);
|
||||
} catch (error) {
|
||||
if (!["ENOENT", "EEXIST"].includes(error.code)) throw error;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
} else if (Date.now() - fs4.statSync(lockDirectory).mtimeMs > 1e4) throw hostError("\u542F\u52A8\u9501\u7F3A\u5C11\u539F\u8BB0\u5F55\uFF0C\u8BF7\u6838\u5BF9\u8BE5\u76EE\u5F55\u3002");
|
||||
if (Date.now() >= deadline) throw hostError("\u6B63\u5728\u7B49\u5F85\u539F\u542F\u52A8\u64CD\u4F5C\uFF0C\u8BF7\u6838\u5BF9\u5F53\u524D\u5BBF\u4E3B\u3002", "HOST_START_PENDING");
|
||||
await delay(100);
|
||||
}
|
||||
}
|
||||
const ownerFile = path5.join(lockDirectory, "owner.json");
|
||||
try {
|
||||
writeState(ownerFile, { schema: 1, pid: process.pid, createdAt: observed.createdAt, userSid: observed.userSid, nonce });
|
||||
return await action();
|
||||
} finally {
|
||||
if (fs4.existsSync(ownerFile) && readState(ownerFile).nonce === nonce) {
|
||||
fs4.unlinkSync(ownerFile);
|
||||
fs4.rmdirSync(lockDirectory);
|
||||
}
|
||||
}
|
||||
}
|
||||
async start() {
|
||||
return this.lock(async () => {
|
||||
const existing = await this.connect();
|
||||
if (existing) return { ...existing, reused: true };
|
||||
const intentFile = ownedChild(this.dataRoot, "desktop-launch-state.json", { missing: true });
|
||||
if (fs4.existsSync(intentFile)) {
|
||||
const intent = readState(intentFile);
|
||||
if (intent.pid && !["exited", "failed"].includes(intent.state)) {
|
||||
const actual = observeWindowsProcess(intent.pid);
|
||||
if (actual && actual.createdAt === intent.createdAt) throw hostError("\u539F\u542F\u52A8\u8FDB\u7A0B\u4ECD\u6D3B\u52A8\u4F46\u6CA1\u6709\u53EF\u6838\u9A8C\u63A5\u53E3\uFF0C\u8BF7\u6838\u5BF9\u539F\u65E5\u5FD7\uFF1B\u4E0D\u4F1A\u518D\u542F\u52A8\u53E6\u4E00\u8FDB\u7A0B\u3002", "HOST_START_UNVERIFIED");
|
||||
}
|
||||
}
|
||||
const logs = ownedChild(this.dataRoot, "logs", { missing: true });
|
||||
if (!fs4.existsSync(logs)) fs4.mkdirSync(logs);
|
||||
const id = randomUUID2(), stdoutPath = path5.join(logs, "desktop-host-" + id + "-stdout.log"), stderrPath = path5.join(logs, "desktop-host-" + id + "-stderr.log");
|
||||
let output, errors, child;
|
||||
try {
|
||||
output = fs4.openSync(stdoutPath, "wx", 384);
|
||||
errors = fs4.openSync(stderrPath, "wx", 384);
|
||||
child = spawn(this.node.path, [ownedChild(this.appRoot, "dist-server/server.mjs")], {
|
||||
cwd: this.appRoot,
|
||||
windowsHide: true,
|
||||
detached: true,
|
||||
env: projectEnvironment({ ...this.environment, AGENT_WORKBENCH_APP_DIR: this.appRoot, AGENT_WORKBENCH_DATA_DIR: this.dataRoot, AGENT_WORKBENCH_PORT: String(this.port) }),
|
||||
stdio: ["ignore", output, errors]
|
||||
});
|
||||
} finally {
|
||||
if (output !== void 0) fs4.closeSync(output);
|
||||
if (errors !== void 0) fs4.closeSync(errors);
|
||||
}
|
||||
let failure = null;
|
||||
child.on("error", (cause) => {
|
||||
failure = cause;
|
||||
});
|
||||
child.unref();
|
||||
const observedChild = child.pid ? observeWindowsProcess(child.pid) : null;
|
||||
writeState(intentFile, {
|
||||
schema: 1,
|
||||
state: observedChild ? "starting" : "failed",
|
||||
id,
|
||||
pid: child.pid ?? null,
|
||||
createdAt: observedChild?.createdAt ?? null,
|
||||
appRoot: this.appRoot,
|
||||
dataRoot: this.dataRoot,
|
||||
port: this.port,
|
||||
stdoutPath,
|
||||
stderrPath
|
||||
});
|
||||
const deadline = Date.now() + this.timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
if (failure || child.exitCode !== null) throw hostError("\u6240\u5C5E\u5BBF\u4E3B\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u67E5\u770B\u672C\u673A\u542F\u52A8\u8BB0\u5F55\u3002", "HOST_START_FAILED");
|
||||
await delay(100);
|
||||
let health;
|
||||
try {
|
||||
health = await this.health();
|
||||
} catch (cause) {
|
||||
if (cause.code !== "HOST_PORT_UNVERIFIED") throw cause;
|
||||
const waiting = observeWindowsProcess(child.pid);
|
||||
if (!waiting || !observedChild || waiting.createdAt !== observedChild.createdAt || waiting.userSid !== observedChild.userSid || !samePath(waiting.executable, this.node.path)) throw hostError("\u6240\u5C5E\u5BBF\u4E3B\u542F\u52A8\u8FDB\u7A0B\u5DF2\u7ED3\u675F\u6216\u8EAB\u4EFD\u53D8\u5316\uFF0C\u8BF7\u6838\u5BF9\u539F\u65E5\u5FD7\u3002", "HOST_START_FAILED");
|
||||
continue;
|
||||
}
|
||||
if (!health) continue;
|
||||
if (health.pid !== child.pid) throw hostError("\u542F\u52A8\u671F\u95F4\u7AEF\u53E3\u88AB\u5176\u4ED6\u8FDB\u7A0B\u5360\u7528\u3002");
|
||||
const connected = await this.connect();
|
||||
if (connected) {
|
||||
writeState(intentFile, { ...readState(intentFile), state: "ready", instanceId: connected.identity.instanceId });
|
||||
return { ...connected, reused: false, logs: { stdoutPath, stderrPath } };
|
||||
}
|
||||
}
|
||||
throw hostError("\u6240\u5C5E\u5BBF\u4E3B\u5C1A\u672A\u5B8C\u6210\u6CE8\u518C\uFF1B\u4E0D\u4F1A\u91CD\u65B0\u542F\u52A8\u6216\u7ED3\u675F\u672A\u77E5\u8FDB\u7A0B\u3002", "HOST_START_UNVERIFIED");
|
||||
});
|
||||
}
|
||||
async status() {
|
||||
if (!await this.connect()) return { state: "not-running", url: this.url };
|
||||
return this.api("/host/status");
|
||||
}
|
||||
async stop() {
|
||||
return this.lock(async () => {
|
||||
const connection = await this.connect();
|
||||
if (!connection) return { state: "not-running", url: this.url };
|
||||
const original = connection.identity;
|
||||
await this.api("/host/stop", { method: "POST", input: {
|
||||
instanceId: original.instanceId,
|
||||
createdAt: original.createdAt,
|
||||
runtimeIdentity: original.runtimeIdentity,
|
||||
confirmation: "stop-owned-host"
|
||||
}, timeoutMs: this.timeoutMs });
|
||||
const deadline = Date.now() + this.timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
await delay(200);
|
||||
const observed = observeWindowsProcess(original.pid);
|
||||
if (!observed) {
|
||||
if (await this.health()) throw hostError("\u539F\u5BBF\u4E3B\u5DF2\u7ED3\u675F\uFF0C\u4F46\u7AEF\u53E3\u5B58\u5728\u5176\u4ED6\u670D\u52A1\u3002");
|
||||
return { state: "stopped", identity: original, processExited: true };
|
||||
}
|
||||
if (observed.createdAt !== original.createdAt) throw hostError("\u539FPID\u5DF2\u88AB\u590D\u7528\uFF0C\u4E0D\u4F1A\u7ED3\u675F\u65B0\u7684\u8FDB\u7A0B\u3002");
|
||||
}
|
||||
throw hostError("\u6240\u5C5E\u5BBF\u4E3B\u9000\u51FA\u4ECD\u5F85\u6838\u5BF9\uFF0C\u8BF7\u4FDD\u7559\u539F\u5B9E\u4F8B\u8BB0\u5F55\u3002", "HOST_STOP_UNVERIFIED");
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// src/desktop/host-cli.mjs
|
||||
var args = process.argv.slice(2);
|
||||
if (args.includes("--help")) {
|
||||
console.log("node host-launcher.mjs <start|status|stop> [--app-root <absolute>] [--data-root <absolute>] [--node <absolute>] [--port <1..65535>]");
|
||||
process.exit(0);
|
||||
}
|
||||
var command = args.shift();
|
||||
if (!["start", "status", "stop"].includes(command)) throw new Error("Use --help for a supported desktop host operation.");
|
||||
var options = {};
|
||||
while (args.length) {
|
||||
const flag = args.shift(), value = args.shift();
|
||||
if (!["--app-root", "--data-root", "--node", "--port"].includes(flag) || !value || options[flag] !== void 0) throw new Error("Invalid or repeated host option.");
|
||||
options[flag] = value;
|
||||
}
|
||||
var defaultRoot = path6.resolve(path6.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
var appRoot = options["--app-root"] || process.env.AGENT_WORKBENCH_APP_DIR || defaultRoot;
|
||||
var dataRoot = options["--data-root"] || process.env.AGENT_WORKBENCH_DATA_DIR || path6.join(process.env.LOCALAPPDATA || path6.join(os.homedir(), ".local/share"), "AgentWorkbench");
|
||||
var nodePath = options["--node"] || (fs5.existsSync(path6.join(appRoot, "runtime/node.exe")) ? path6.join(appRoot, "runtime/node.exe") : process.execPath);
|
||||
try {
|
||||
const controller = new HostController({
|
||||
appRoot,
|
||||
dataRoot,
|
||||
nodePath,
|
||||
port: Number(options["--port"] || process.env.AGENT_WORKBENCH_PORT || 4318),
|
||||
environment: Object.fromEntries(HOST_ENVIRONMENT.filter((key) => process.env[key]).map((key) => [key, process.env[key]]))
|
||||
});
|
||||
console.log(JSON.stringify(await controller[command]()));
|
||||
} catch (cause) {
|
||||
console.error(JSON.stringify({ success: false, code: cause.code || "HOST_FAILED", message: cause.message }));
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -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 @@
|
||||
{ "unfinished":
|
||||
@@ -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>
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"name": "local-agent-workbench",
|
||||
"version": "1.24.4",
|
||||
"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"}]}
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
|
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,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))}));
|
||||