@christang/keel 5.229.3 → 5.231.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +10 -2
- package/README.zh-CN.md +7 -1
- package/assets/bootstrap/AGENTS.md +1 -1
- package/bin/keel.js +6 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/plugins/keel/.claude-plugin/plugin.json +1 -1
- package/plugins/keel/.codex-plugin/plugin.json +1 -1
- package/scripts/test_codex_host.js +167 -0
- package/scripts/test_codex_onboarding.js +243 -0
- package/scripts/validation/codexhost.py +1 -1
- package/scripts/validation/common.py +2 -2
- package/src/core/codex-host.js +66 -16
- package/src/core/codex-onboarding.js +291 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.231.0",
|
|
4
4
|
"description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "TanglmChris",
|
package/README.md
CHANGED
|
@@ -121,8 +121,16 @@ If receiving hooks are unavailable, use `keel mail list` and `keel mail read`
|
|
|
121
121
|
explicitly. For a team owned by Keel, use `keel codex start --role <role> --repo <worktree>`
|
|
122
122
|
with a reachable Codex app-server endpoint (`--socket <path>` selects one explicitly).
|
|
123
123
|
`keel codex drain` and `keel tick` deliver addressed records to those managed roles;
|
|
124
|
-
`keel codex handover` retains a note and creates a successor only after the role is idle
|
|
125
|
-
|
|
124
|
+
`keel codex handover` retains a note and creates a successor only after the role is idle;
|
|
125
|
+
registered original frontends instead require separate successor authorization.
|
|
126
|
+
An explicitly authorized dedicated original thread can use `keel codex inspect-registration`
|
|
127
|
+
with `--thread`, `--socket` and `--authority`, then `keel codex register --plan <file>`.
|
|
128
|
+
For owned endpoint changes, `keel codex inspect-migration --to-socket <path>` prepares
|
|
129
|
+
an exact plan; `keel codex migrate --plan <file>` applies it. Inspect uncertain outcomes
|
|
130
|
+
with `keel codex migration-status --plan <file>`; `--reconcile` verifies an already loaded
|
|
131
|
+
original target, without retrying an unloaded acquisition. Original identity/history/claims
|
|
132
|
+
and approved native policy remain; arbitrary desktop chats are not automatically adopted.
|
|
133
|
+
See [the team runbook](docs/cli-team.md) for source input admission and failure handling. Native write-guard enforcement and compaction
|
|
126
134
|
remain manual until the current installation is behaviorally verified.
|
|
127
135
|
See the [Codex acceptance record](docs/codex-validation.md) for versions, runtime
|
|
128
136
|
evidence, limitations and the clean-consumer Full-mode check.
|
package/README.zh-CN.md
CHANGED
|
@@ -133,7 +133,13 @@ rm -rf "$tmp_dir"
|
|
|
133
133
|
|
|
134
134
|
Keel 托管的 Codex 团队通过 `keel codex start --role <role> --repo <worktree>` 创建角色,
|
|
135
135
|
`--socket <path>` 指定可连接的 app-server 套接字。`keel codex drain` 和 `keel tick`
|
|
136
|
-
只投递发给该角色的记录;`keel codex handover`
|
|
136
|
+
只投递发给该角色的记录;`keel codex handover` 在旧式角色空闲后保留说明并创建后继,
|
|
137
|
+
已登记前台的后继须另有授权。已明确授权的专用原线程可用 `keel codex inspect-registration`
|
|
138
|
+
配合 `--thread`、`--socket`、`--authority` 检查,再用 `keel codex register --plan <file>` 登记。
|
|
139
|
+
自有角色端点变化用 `keel codex inspect-migration --to-socket <path>` 制定精确计划,
|
|
140
|
+
`keel codex migrate --plan <file>` 执行;未知结果先看 `keel codex migration-status --plan <file>`,
|
|
141
|
+
`--reconcile` 只核已加载的目标原线程,不重新获取未加载目标。原身份、历史、声明和批准的原生
|
|
142
|
+
策略保留,源输入准入和失败处理见团队说明。
|
|
137
143
|
现有桌面聊天不会被自动接管。原生写入拦截和压缩后的重新注入仍需当前安装的实际验证,能力报告保持 manual。
|
|
138
144
|
详见 [Codex 验收记录](docs/codex-validation.md) 和 [CLI 团队说明](docs/cli-team.zh-CN.md)。
|
|
139
145
|
|
package/bin/keel.js
CHANGED
|
@@ -107,7 +107,12 @@ Usage:
|
|
|
107
107
|
keel worktrees [--repo <path>] [--issues <file>] [--json] (read-only worktree overview)
|
|
108
108
|
keel sync status [--repo <path>] [--verify] [--remote <name>] [--json] (what exists only on this machine; fetches nothing, --verify asks the remote its sha)
|
|
109
109
|
keel patrol [--issues <file>] [--idle <dur>] [--since-last [--notify]] [--nudge] [--json] [--repo <path>] (the coordinator's patrol; keel patrol task prints its schedule)
|
|
110
|
-
keel codex status|start|deliver|handover|drain [--repo <path>] [--role <role>] [--socket <path>] [--json] (managed Codex roles; explicit host identity)
|
|
110
|
+
keel codex status|start|deliver|handover|drain|recover [--repo <path>] [--role <role>] [--socket <path>] [--json] (managed Codex roles; explicit host identity)
|
|
111
|
+
keel codex inspect-registration --repo <path> --role <role> --thread <id> --socket <path> --authority <reference>
|
|
112
|
+
keel codex register --plan <json-file> [--json]
|
|
113
|
+
keel codex inspect-migration --repo <path> --role <role> --to-socket <path> --authority <reference>
|
|
114
|
+
keel codex migrate --plan <json-file> [--reconcile] [--json]
|
|
115
|
+
keel codex migration-status --plan <json-file> [--json]
|
|
111
116
|
keel tick [--repo <path>] [--json] (one model-free step for a host scheduler; keel tick task prints the job)
|
|
112
117
|
keel openspec [args...]
|
|
113
118
|
keel --init [repo] [--target claude|codex|opencode|dsh] [--dry-run] [--force-template-update]
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@christang/keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.231.0",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@christang/keel",
|
|
9
|
-
"version": "5.
|
|
9
|
+
"version": "5.231.0",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@fission-ai/openspec": "1.14.0"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.231.0",
|
|
4
4
|
"description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "TanglmChris",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.231.0",
|
|
4
4
|
"description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "TanglmChris",
|
|
@@ -123,3 +123,170 @@ test('tick renders managed host failures without starting a replacement', async
|
|
|
123
123
|
assert.match(result.out,/Codex bad-role.*unverified/);
|
|
124
124
|
} finally {fs.rmSync(dir,{recursive:true,force:true});}
|
|
125
125
|
});
|
|
126
|
+
|
|
127
|
+
// A native protocol boundary fixture; the public CLI and store run unchanged.
|
|
128
|
+
async function reviewerHost() {
|
|
129
|
+
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'keel-reviewer-'));
|
|
130
|
+
require('node:child_process').spawnSync('git',['init','-q',dir]);
|
|
131
|
+
const sock=path.join(dir,'host.sock'),requests=[],threads=new Map(),peers=[],turnReviewers=[];
|
|
132
|
+
let serial=0,rejectPersistence=false,mismatch=false,dropStartReply=false;
|
|
133
|
+
const server=http.createServer();
|
|
134
|
+
server.on('upgrade',(req,s)=>{
|
|
135
|
+
peers.push(s);s.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: '+crypto.createHash('sha1').update(req.headers['sec-websocket-key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64')+'\r\n\r\n');
|
|
136
|
+
let buf=Buffer.alloc(0);s.on('end',()=>{for(const t of threads.values()){t.loaded=false;t.reviewer=t.savedReviewer;}});
|
|
137
|
+
s.on('data',chunk=>{buf=Buffer.concat([buf,chunk]);while(buf.length>=6){let n=buf[1]&127,off=2;if(n===126){if(buf.length<8)return;n=buf.readUInt16BE(2);off=4;}else if(n===127){if(buf.length<14)return;n=Number(buf.readBigUInt64BE(2));off=10;}if(buf.length<off+4+n)return;const mask=buf.subarray(off,off+4),data=Buffer.from(buf.subarray(off+4,off+4+n));buf=buf.subarray(off+4+n);for(let i=0;i<data.length;i++)data[i]^=mask[i%4];const x=JSON.parse(data);requests.push(x);if(!x.id)continue;
|
|
138
|
+
let result={},error;const p=x.params||{};let t=threads.get(p.threadId);
|
|
139
|
+
const reply=()=>({thread:{id:t.id,cwd:t.cwd||dir,status:{type:t.status||(t.loaded?'idle':'notLoaded')}},approvalsReviewer:mismatch?'user':t.reviewer,approvalPolicy:'on-request',sandbox:{type:'workspaceWrite',networkAccess:false,writableRoots:[]}});
|
|
140
|
+
if(x.method==='initialize')result={userAgent:'native-reviewer-fixture'};
|
|
141
|
+
else if(x.method==='thread/start'){t={id:'reviewer-'+ ++serial,reviewer:p.approvalsReviewer||'user',savedReviewer:'user',loaded:true};threads.set(t.id,t);result=reply();}
|
|
142
|
+
else if(x.method==='thread/name/set'){}
|
|
143
|
+
else if(x.method==='thread/settings/update'){if(rejectPersistence)error={message:'native reviewer persistence rejected'};else t.savedReviewer=t.reviewer=p.approvalsReviewer;}
|
|
144
|
+
else if(x.method==='thread/read')result=reply();
|
|
145
|
+
else if(x.method==='thread/resume'){if(t.resumeError)error={message:t.resumeError};else {t.loaded=true;t.cwd=p.cwd||t.cwd;t.reviewer=p.approvalsReviewer||t.savedReviewer;result=reply();if(t.wrongResumeCwd)result.thread.cwd='/wrong-resumed-cwd';}}
|
|
146
|
+
else if(x.method==='turn/start'){t.reviewer=p.approvalsReviewer||t.reviewer;turnReviewers.push(t.reviewer);t.savedReviewer=t.reviewer;result={turn:{id:'reviewer-turn-'+turnReviewers.length}};}
|
|
147
|
+
else error={message:'unsupported fixture RPC '+x.method};
|
|
148
|
+
if(dropStartReply&&x.method==='thread/start')continue;
|
|
149
|
+
const body=Buffer.from(JSON.stringify({id:x.id,...error?{error}:{result}}));const h=body.length<126?Buffer.from([129,body.length]):Buffer.from([129,126,body.length>>8,body.length&255]);s.write(Buffer.concat([h,body]));
|
|
150
|
+
}});
|
|
151
|
+
});
|
|
152
|
+
await new Promise(r=>server.listen(sock,r));
|
|
153
|
+
return {dir,sock,requests,threads,turnReviewers,dropStartReply:()=>{dropStartReply=true;},rejectPersistence:()=>{rejectPersistence=true;},mismatch:()=>{mismatch=true;},args:(reviewer='auto_review')=>['--socket',sock,'--repo',dir,'--role','reviewer-worker','--approvals-reviewer',reviewer,'--json'],close:async()=>{peers.forEach(p=>p.destroy());await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});}};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
test('explicit thread reviewer persists before managed success without a model turn',async()=>{
|
|
157
|
+
const h=await reviewerHost();try{
|
|
158
|
+
const r=await run(h.args(),'start');assert.equal(r.code,0,r.err);
|
|
159
|
+
const entry=JSON.parse(r.out);assert.equal(entry.approvalsReviewer,'auto_review');
|
|
160
|
+
assert.equal(h.threads.get(entry.thread).savedReviewer,'auto_review');
|
|
161
|
+
assert.equal(h.requests.filter(x=>x.method==='turn/start').length,0);
|
|
162
|
+
const init=h.requests.find(x=>x.method==='initialize');assert.equal(init.params.capabilities.experimentalApi,true);
|
|
163
|
+
assert.ok(h.requests.findIndex(x=>x.method==='thread/settings/update')>h.requests.findIndex(x=>x.method==='thread/start'));
|
|
164
|
+
}finally{await h.close();}
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
test('explicit thread reviewer controls cold delivery after native policy drift',async()=>{
|
|
169
|
+
const h=await reviewerHost();try{
|
|
170
|
+
const r=await run(h.args(),'start');assert.equal(r.code,0,r.err);
|
|
171
|
+
const id=JSON.parse(r.out).thread;h.threads.get(id).savedReviewer='user';h.threads.get(id).loaded=false;
|
|
172
|
+
const delivered=await run(['--repo',h.dir,'--role','reviewer-worker','--record','reviewer-delivery','--text','explicit policy work','--json'],'deliver');
|
|
173
|
+
assert.equal(delivered.code,0,delivered.err);assert.deepEqual(h.turnReviewers,['auto_review']);
|
|
174
|
+
assert.equal(h.requests.filter(x=>x.method==='thread/start').length,1,'cold delivery retains original id');
|
|
175
|
+
}finally{await h.close();}
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
test('explicit thread reviewer persists on handover successor',async()=>{
|
|
179
|
+
const h=await reviewerHost();try{
|
|
180
|
+
const r=await run(h.args(),'start');assert.equal(r.code,0,r.err);
|
|
181
|
+
const original=JSON.parse(r.out).thread;h.threads.get(original).loaded=true;
|
|
182
|
+
const handed=await run(['--repo',h.dir,'--role','reviewer-worker','--note','retained authority','--json'],'handover');
|
|
183
|
+
assert.equal(handed.code,0,handed.err);const next=JSON.parse(handed.out).thread;
|
|
184
|
+
assert.notEqual(next,original);assert.equal(h.threads.get(next).savedReviewer,'auto_review');
|
|
185
|
+
const role=JSON.parse(fs.readFileSync(path.join(h.dir,'.git/keel-chat/codex-roles/reviewer-worker.json')));
|
|
186
|
+
assert.equal(role.approvalsReviewer,'auto_review');assert.equal(role.history[0].thread,original);
|
|
187
|
+
assert.equal(h.requests.filter(x=>x.method==='turn/start').length,0);
|
|
188
|
+
}finally{await h.close();}
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
test('explicit thread reviewer rejects native policy mismatch without losing id',async()=>{
|
|
192
|
+
const h=await reviewerHost();try{
|
|
193
|
+
h.mismatch();const r=await run(h.args(),'start');assert.notEqual(r.code,0,'policy mismatch must not report managed success');
|
|
194
|
+
assert.match(r.err,/reviewer mismatch/);
|
|
195
|
+
const role=JSON.parse(fs.readFileSync(path.join(h.dir,'.git/keel-chat/codex-roles/reviewer-worker.json')));
|
|
196
|
+
assert.equal(role.state,'creation-pending');assert.equal(role.thread,'reviewer-1');
|
|
197
|
+
const retry=await run(h.args(),'start');assert.notEqual(retry.code,0);
|
|
198
|
+
assert.equal(h.requests.filter(x=>x.method==='thread/start').length,1);
|
|
199
|
+
assert.equal(h.requests.filter(x=>x.method==='turn/start').length,0);
|
|
200
|
+
}finally{await h.close();}
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
test('explicit user reviewer and invalid start flags leave native boundaries intact',async()=>{
|
|
204
|
+
const h=await reviewerHost();try{
|
|
205
|
+
for(const [action,args,message]of [['start',h.args('never'),/must be user or auto_review/],['status',h.args(),/only accepted by start/],['deliver',h.args(),/only accepted by start/]]){
|
|
206
|
+
const r=await run(args,action);assert.notEqual(r.code,0);assert.match(r.err,message);
|
|
207
|
+
}
|
|
208
|
+
assert.equal(h.requests.length,0,'invalid flag/action must reach no native RPC');
|
|
209
|
+
const r=await run(h.args('user'),'start');assert.equal(r.code,0,r.err);
|
|
210
|
+
assert.equal(h.threads.get(JSON.parse(r.out).thread).savedReviewer,'user');
|
|
211
|
+
assert.equal(h.requests.find(x=>x.method==='thread/start').params.sandbox,'workspace-write');
|
|
212
|
+
assert.equal(h.requests.find(x=>x.method==='thread/start').params.approvalPolicy,'on-request');
|
|
213
|
+
}finally{await h.close();}
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test('explicit thread reviewer persistence failure retains pending creation identity',async()=>{
|
|
217
|
+
const h=await reviewerHost();try{
|
|
218
|
+
h.rejectPersistence();const r=await run(h.args(),'start');assert.notEqual(r.code,0);assert.match(r.err,/native reviewer persistence rejected/);
|
|
219
|
+
const role=JSON.parse(fs.readFileSync(path.join(h.dir,'.git/keel-chat/codex-roles/reviewer-worker.json')));
|
|
220
|
+
assert.equal(role.state,'creation-pending');assert.equal(role.thread,'reviewer-1');
|
|
221
|
+
assert.equal((await run(h.args(),'start')).code,1);assert.equal(h.threads.size,1);
|
|
222
|
+
assert.equal(h.requests.filter(x=>x.method==='turn/start').length,0);
|
|
223
|
+
}finally{await h.close();}
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
test('explicit thread reviewer successor persistence failure keeps old and pending ids',async()=>{
|
|
227
|
+
const h=await reviewerHost();try{
|
|
228
|
+
const r=await run(h.args(),'start');assert.equal(r.code,0,r.err);const original=JSON.parse(r.out).thread;
|
|
229
|
+
h.threads.get(original).loaded=true;h.rejectPersistence();
|
|
230
|
+
const args=['--repo',h.dir,'--role','reviewer-worker','--note','keep pending successor','--json'];
|
|
231
|
+
const handed=await run(args,'handover');assert.notEqual(handed.code,0);assert.match(handed.err,/native reviewer persistence rejected/);
|
|
232
|
+
const role=JSON.parse(fs.readFileSync(path.join(h.dir,'.git/keel-chat/codex-roles/reviewer-worker.json')));
|
|
233
|
+
assert.equal(role.thread,original);assert.equal(role.handover.thread,'reviewer-2');assert.equal(role.approvalsReviewer,'auto_review');
|
|
234
|
+
h.threads.get(original).loaded=true;assert.notEqual((await run(args,'handover')).code,0);
|
|
235
|
+
assert.equal(h.threads.size,2);assert.equal(h.requests.filter(x=>x.method==='turn/start').length,0);
|
|
236
|
+
}finally{await h.close();}
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
test('explicit thread reviewer mismatch on resume starts no delivery',async()=>{
|
|
240
|
+
const h=await reviewerHost();try{
|
|
241
|
+
const r=await run(h.args(),'start');assert.equal(r.code,0,r.err);h.mismatch();
|
|
242
|
+
const delivered=await run(['--repo',h.dir,'--role','reviewer-worker','--record','not-started','--text','policy mismatch','--json'],'deliver');
|
|
243
|
+
assert.notEqual(delivered.code,0);assert.match(delivered.err,/reviewer mismatch/);
|
|
244
|
+
assert.equal(h.requests.filter(x=>x.method==='turn/start').length,0);assert.equal(h.threads.size,1);
|
|
245
|
+
}finally{await h.close();}
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
test('explicit thread reviewer remains declared when creation response is unknown',async()=>{
|
|
250
|
+
const h=await reviewerHost();try{
|
|
251
|
+
h.dropStartReply();const r=await run([...h.args(),'--timeout','300'],'start');assert.notEqual(r.code,0);assert.match(r.err,/thread\/start timeout/);
|
|
252
|
+
const role=JSON.parse(fs.readFileSync(path.join(h.dir,'.git/keel-chat/codex-roles/reviewer-worker.json')));
|
|
253
|
+
assert.equal(role.state,'creation-pending');assert.equal(role.approvalsReviewer,'auto_review');assert.equal(role.thread,undefined);
|
|
254
|
+
assert.notEqual((await run(h.args(),'start')).code,0);assert.equal(h.threads.size,1);
|
|
255
|
+
}finally{await h.close();}
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
test('recover restores original owned cwd without rewriting role claims or starting work',async()=>{
|
|
260
|
+
const h=await reviewerHost();try{
|
|
261
|
+
const started=await run(h.args(),'start');assert.equal(started.code,0,started.err);const id=JSON.parse(started.out).thread;
|
|
262
|
+
const delivered=await run(['--repo',h.dir,'--role','reviewer-worker','--record','prior-claim','--text','prior work','--json'],'deliver');assert.equal(delivered.code,0,delivered.err);
|
|
263
|
+
const file=path.join(h.dir,'.git/keel-chat/codex-roles/reviewer-worker.json'),before=fs.readFileSync(file);
|
|
264
|
+
h.threads.get(id).cwd='/drifted-cwd';h.threads.get(id).loaded=false;
|
|
265
|
+
const turnCount=h.requests.filter(x=>x.method==='turn/start').length;
|
|
266
|
+
const result=await run(['--repo',h.dir,'--role','reviewer-worker','--json'],'recover');assert.equal(result.code,0,result.err);
|
|
267
|
+
assert.equal(JSON.parse(result.out).state,'recovered');assert.equal(JSON.parse(result.out).thread,id);
|
|
268
|
+
const resume=h.requests.filter(x=>x.method==='thread/resume').at(-1);
|
|
269
|
+
assert.equal(resume.params.cwd,h.dir);assert.deepEqual(resume.params.runtimeWorkspaceRoots,[h.dir]);assert.equal(resume.params.threadId,id);
|
|
270
|
+
assert.equal(resume.params.approvalsReviewer,'auto_review');assert.deepEqual(fs.readFileSync(file),before);
|
|
271
|
+
assert.equal(h.requests.filter(x=>x.method==='turn/start').length,turnCount);assert.equal(h.requests.filter(x=>x.method==='thread/start').length,1);
|
|
272
|
+
}finally{await h.close();}
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
test('recover refuses unsafe native and role boundaries without changing records',async()=>{
|
|
276
|
+
const h=await reviewerHost();try{
|
|
277
|
+
const started=await run(h.args(),'start');assert.equal(started.code,0,started.err);const id=JSON.parse(started.out).thread,t=h.threads.get(id);
|
|
278
|
+
const file=path.join(h.dir,'.git/keel-chat/codex-roles/reviewer-worker.json'),before=fs.readFileSync(file);
|
|
279
|
+
const args=['--repo',h.dir,'--role','reviewer-worker','--json'];
|
|
280
|
+
t.cwd='/drifted-cwd';t.status='active';let count=h.requests.filter(x=>x.method==='thread/resume').length;
|
|
281
|
+
const busy=await run(args,'recover');assert.equal(busy.code,0,busy.err);assert.equal(JSON.parse(busy.out).state,'waiting');assert.equal(h.requests.filter(x=>x.method==='thread/resume').length,count);
|
|
282
|
+
t.status='idle';t.id='foreign-thread';const wrongId=await run(args,'recover');assert.notEqual(wrongId.code,0);assert.match(wrongId.err,/identity/);assert.equal(h.requests.filter(x=>x.method==='thread/resume').length,count);t.id=id;
|
|
283
|
+
t.status='unknown';const unknown=await run(args,'recover');assert.notEqual(unknown.code,0);assert.match(unknown.err,/state/);assert.equal(h.requests.filter(x=>x.method==='thread/resume').length,count);
|
|
284
|
+
t.status='idle';t.resumeError='already has an active writer';const writer=await run(args,'recover');assert.notEqual(writer.code,0);assert.match(writer.err,/active writer/);delete t.resumeError;
|
|
285
|
+
t.wrongResumeCwd=true;const mismatch=await run(args,'recover');assert.notEqual(mismatch.code,0);assert.match(mismatch.err,/identity/);delete t.wrongResumeCwd;
|
|
286
|
+
h.mismatch();const policy=await run(args,'recover');assert.notEqual(policy.code,0);assert.match(policy.err,/reviewer mismatch/);
|
|
287
|
+
count=h.requests.length;const endpoint=await run([...args,'--socket',path.join(h.dir,'wrong.sock')],'recover');assert.notEqual(endpoint.code,0);assert.match(endpoint.err,/endpoint mismatch/);assert.equal(h.requests.length,count);
|
|
288
|
+
const unowned=await run(['--repo',h.dir,'--role','unowned','--json'],'recover');assert.notEqual(unowned.code,0);assert.equal(h.requests.length,count);
|
|
289
|
+
const noRole=await run(['--repo',h.dir,'--json'],'recover');assert.notEqual(noRole.code,0);assert.equal(h.requests.length,count);
|
|
290
|
+
assert.deepEqual(fs.readFileSync(file),before);assert.equal(h.requests.filter(x=>x.method==='thread/start').length,1);assert.equal(h.requests.filter(x=>x.method==='turn/start').length,0);
|
|
291
|
+
}finally{await h.close();}
|
|
292
|
+
});
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const {test}=require('node:test');
|
|
3
|
+
const assert=require('node:assert/strict');
|
|
4
|
+
const fs=require('node:fs');
|
|
5
|
+
const os=require('node:os');
|
|
6
|
+
const path=require('node:path');
|
|
7
|
+
const crypto=require('node:crypto');
|
|
8
|
+
const http=require('node:http');
|
|
9
|
+
const {spawn,spawnSync}=require('node:child_process');
|
|
10
|
+
const cli=path.resolve(__dirname,'../bin/keel.js');
|
|
11
|
+
function run(action,args){return new Promise(resolve=>{const p=spawn(process.execPath,[cli,'codex',action,...args],{env:{...process.env,KEEL_CHAT_ROLE:'',KEEL_MAIL_ROLE:''}});let out='',err='';p.stdout.on('data',b=>out+=b);p.stderr.on('data',b=>err+=b);p.on('close',code=>resolve({code,out,err}));});}
|
|
12
|
+
async function fixture(){
|
|
13
|
+
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'keel-onboard-test-'));
|
|
14
|
+
assert.equal(spawnSync('git',['init','-q',dir]).status,0);
|
|
15
|
+
const root=path.join(dir,'.git/keel-chat');fs.mkdirSync(root,{recursive:true});
|
|
16
|
+
const role='review',thread='original-review';fs.writeFileSync(path.join(root,'roles.json'),JSON.stringify({[dir]:role}));
|
|
17
|
+
const record=path.join(root,'codex-roles',role+'.json');
|
|
18
|
+
const native={id:thread,cwd:dir,status:'idle',turns:[{id:'previous-turn',status:'completed',items:[{id:'previous-answer',type:'agentMessage',text:'original result'}]}],policy:{approvalPolicy:'on-request',approvalsReviewer:'user',sandbox:{type:'readOnly',networkAccess:false},runtimeWorkspaceRoots:[dir]},loaded:'source'};
|
|
19
|
+
const requests=[],peers=[],servers=[],controls={};
|
|
20
|
+
async function host(name){
|
|
21
|
+
const sock=path.join(dir,name+'.sock'),server=http.createServer();servers.push(server);
|
|
22
|
+
server.on('upgrade',(req,s)=>{peers.push(s);s.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: '+crypto.createHash('sha1').update(req.headers['sec-websocket-key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64')+'\r\n\r\n');let buf=Buffer.alloc(0);
|
|
23
|
+
s.on('data',chunk=>{buf=Buffer.concat([buf,chunk]);while(buf.length>=6){let len=buf[1]&127,offset=2;if(len===126){if(buf.length<8)return;len=buf.readUInt16BE(2);offset=4;}else if(len===127){if(buf.length<14)return;len=Number(buf.readBigUInt64BE(2));offset=10;}if(buf.length<offset+4+len)return;const mask=buf.subarray(offset,offset+4),body=Buffer.from(buf.subarray(offset+4,offset+4+len));buf=buf.subarray(offset+4+len);for(let i=0;i<body.length;i++)body[i]^=mask[i%4];const x=JSON.parse(body);requests.push({host:name,...x});if(!x.id)continue;
|
|
24
|
+
const p=x.params||{};let result={},error;
|
|
25
|
+
const metadata=()=>({id:(controls.wrongId||(name==='target'&&controls.targetWrongId))?'wrong-id':native.id,cwd:(controls.wrongCwd||(name==='target'&&controls.targetWrongCwd))?'/wrong-cwd':native.cwd,status:{type:native.loaded===name?native.status:'notLoaded'},turns:p.includeTurns?native.turns:[]});
|
|
26
|
+
if(x.method==='initialize')result={userAgent:'native-onboarding-boundary'};
|
|
27
|
+
else if(controls.beforeReply)controls.beforeReply(x,name);
|
|
28
|
+
if(x.method==='thread/read')result={thread:metadata()};
|
|
29
|
+
else if(x.method==='thread/resume'){
|
|
30
|
+
if(native.loaded&&native.loaded!==name)error='original has an active writer';
|
|
31
|
+
else {native.loaded=name;result={thread:metadata(),...structuredClone(native.policy)};if(controls.badPolicy||(name==='target'&&controls.targetBadPolicy))result.sandbox={type:'workspaceWrite'};}
|
|
32
|
+
}else if(x.method==='thread/turns/list'){const start=Number(p.cursor||0);result={data:native.turns.slice(start,start+1),nextCursor:start+1<native.turns.length?String(start+1):null};if(name==='target'&&controls.missingHistory)result={data:[],nextCursor:null};}
|
|
33
|
+
else if(x.method==='thread/queue/list')result={data:controls.queued?[{id:'queued-input'}]:[],nextCursor:null};
|
|
34
|
+
else if(x.method==='thread/goal/get')result={goal:controls.goal?{objective:'original goal'}:null};
|
|
35
|
+
else if(x.method==='thread/backgroundTerminals/list')result={data:controls.terminal?[{id:'running-tool'}]:[],nextCursor:null};
|
|
36
|
+
else if(x.method==='thread/unsubscribe'){if(!controls.retainWriter)native.loaded=null;result={status:'unsubscribed'};}
|
|
37
|
+
else if(x.method==='turn/start'){native.turns.push({id:'delivered-'+native.turns.length,status:'completed',items:[{id:'new-answer',type:'agentMessage',text:p.input[0].text}]});result={turn:native.turns.at(-1)};}
|
|
38
|
+
else if(x.method!=='initialize')error='unsupported RPC '+x.method;
|
|
39
|
+
if(controls.dropAcquire&&name==='target'&&x.method==='thread/resume'){s.destroy();continue;}
|
|
40
|
+
const b=Buffer.from(JSON.stringify({id:x.id,...error?{error:{message:error}}:{result}}));const h=b.length<126?Buffer.from([129,b.length]):Buffer.from([129,126,b.length>>8,b.length&255]);s.write(Buffer.concat([h,b]));
|
|
41
|
+
}});
|
|
42
|
+
});
|
|
43
|
+
await new Promise(r=>server.listen(sock,r));return sock;
|
|
44
|
+
}
|
|
45
|
+
const source=await host('source'),target=await host('target');
|
|
46
|
+
return {dir,root,role,thread,record,native,requests,controls,source,target,
|
|
47
|
+
args:['--repo',dir,'--role',role,'--thread',thread,'--socket',source,'--authority','https://example.com/owner/approved-thread'],
|
|
48
|
+
savePlan(result){assert.equal(result.code,0,result.err);const file=path.join(dir,'plan-'+crypto.randomBytes(4).toString('hex')+'.json');fs.writeFileSync(file,result.out);return file;},
|
|
49
|
+
close:async()=>{peers.forEach(p=>p.destroy());await Promise.all(servers.map(s=>new Promise(r=>s.close(r))));fs.rmSync(dir,{recursive:true,force:true});}};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
test('register original readonly frontend and deliver with unchanged policy',async()=>{
|
|
53
|
+
const h=await fixture();try{
|
|
54
|
+
const before=structuredClone(h.native.turns);
|
|
55
|
+
const plan=h.savePlan(await run('inspect-registration',h.args));
|
|
56
|
+
const r=await run('register',['--plan',plan,'--json']);assert.equal(r.code,0,r.err);
|
|
57
|
+
const entry=JSON.parse(fs.readFileSync(h.record));assert.equal(entry.thread,h.thread);assert.deepEqual(entry.nativePolicy,h.native.policy);
|
|
58
|
+
assert.deepEqual(h.native.turns,before);assert.equal(h.requests.filter(x=>['thread/start','thread/settings/update','turn/start'].includes(x.method)).length,0);
|
|
59
|
+
h.native.loaded=null;
|
|
60
|
+
const args=['--repo',h.dir,'--role',h.role,'--record','coordination-1','--text','Read the assigned review; no edits.','--json'];
|
|
61
|
+
const delivered=await run('deliver',args);assert.equal(delivered.code,0,delivered.err);assert.equal(JSON.parse(delivered.out).state,'delivered');
|
|
62
|
+
const duplicate=await run('deliver',args);assert.equal(duplicate.code,0,duplicate.err);assert.equal(JSON.parse(duplicate.out).state,'already-delivered');
|
|
63
|
+
assert.equal(h.requests.filter(x=>x.method==='turn/start').length,1);assert.deepEqual(h.native.policy,entry.nativePolicy);
|
|
64
|
+
const resumed=h.requests.filter(x=>x.method==='thread/resume');assert.ok(resumed.every(x=>Object.keys(x.params).join(',')==='threadId'),'no permission overrides while inspecting or delivering registered frontend');
|
|
65
|
+
}finally{await h.close();}
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('registration preserves active work and registered recovery preserves original runtime roots',async()=>{
|
|
69
|
+
const h=await fixture();try{
|
|
70
|
+
h.native.status='active';h.native.policy.runtimeWorkspaceRoots=[];
|
|
71
|
+
const plan=h.savePlan(await run('inspect-registration',h.args));
|
|
72
|
+
assert.equal((await run('register',['--plan',plan])).code,0);
|
|
73
|
+
assert.equal(h.native.status,'active');
|
|
74
|
+
const waiting=await run('deliver',['--repo',h.dir,'--role',h.role,'--record','while-busy','--text','do not interrupt','--json']);
|
|
75
|
+
assert.equal(waiting.code,0,waiting.err);assert.equal(JSON.parse(waiting.out).state,'waiting');assert.equal(h.requests.filter(x=>x.method==='turn/start').length,0);
|
|
76
|
+
h.native.status='idle';h.native.loaded=null;
|
|
77
|
+
const recovered=await run('recover',['--repo',h.dir,'--role',h.role,'--json']);assert.equal(recovered.code,0,recovered.err);
|
|
78
|
+
const request=h.requests.filter(x=>x.method==='thread/resume').at(-1);assert.deepEqual(request.params.runtimeWorkspaceRoots,[],'registered recovery must not replace the observed runtime roots');
|
|
79
|
+
const handover=await run('handover',['--repo',h.dir,'--role',h.role,'--note','do not create second review']);assert.notEqual(handover.code,0);assert.match(handover.err,/successor authorization/);assert.equal(h.requests.filter(x=>x.method==='thread/start').length,0);
|
|
80
|
+
}finally{await h.close();}
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('registration rejects unapproved, conflicting, stale and concurrent identities',async()=>{
|
|
84
|
+
const h=await fixture();try{
|
|
85
|
+
for(const args of [h.args.filter((_,i)=>i<h.args.length-2),h.args.map(x=>x===h.role?'keel':x)]){
|
|
86
|
+
const r=await run('inspect-registration',args);assert.notEqual(r.code,0);assert.ok(!fs.existsSync(h.record));
|
|
87
|
+
}
|
|
88
|
+
const plan=h.savePlan(await run('inspect-registration',h.args));
|
|
89
|
+
const originalPlan=fs.readFileSync(plan);let p=JSON.parse(originalPlan);p.thread='not-authorized';fs.writeFileSync(plan,JSON.stringify(p));
|
|
90
|
+
assert.match((await run('register',['--plan',plan])).err,/tampered/);fs.writeFileSync(plan,originalPlan);
|
|
91
|
+
fs.mkdirSync(path.dirname(h.record),{recursive:true});const other=path.join(path.dirname(h.record),'other.json');
|
|
92
|
+
for(const record of [{thread:h.thread},{state:'creation-pending',handover:{thread:h.thread}},{history:[{thread:h.thread}]}]){
|
|
93
|
+
fs.writeFileSync(other,JSON.stringify(record));assert.match((await run('register',['--plan',plan])).err,/another managed role/);assert.ok(!fs.existsSync(h.record));
|
|
94
|
+
}
|
|
95
|
+
fs.writeFileSync(other,'{broken');assert.notEqual((await run('register',['--plan',plan])).code,0);fs.unlinkSync(other);
|
|
96
|
+
const bindings=path.join(h.root,'roles.json'),savedBindings=fs.readFileSync(bindings);
|
|
97
|
+
for(const value of [{[h.dir]:'different'}, {[h.dir]:h.role,'/another-worktree':h.role}]){
|
|
98
|
+
fs.writeFileSync(bindings,JSON.stringify(value));assert.notEqual((await run('register',['--plan',plan])).code,0);assert.ok(!fs.existsSync(h.record));
|
|
99
|
+
}
|
|
100
|
+
fs.writeFileSync(bindings,savedBindings);
|
|
101
|
+
h.controls.badPolicy=true;assert.match((await run('register',['--plan',plan])).err,/policy mismatch/);h.controls.badPolicy=false;
|
|
102
|
+
h.controls.wrongId=true;assert.match((await run('register',['--plan',plan])).err,/identity/);h.controls.wrongId=false;
|
|
103
|
+
h.controls.wrongCwd=true;assert.match((await run('register',['--plan',plan])).err,/worktree/);h.controls.wrongCwd=false;
|
|
104
|
+
const lock=path.join(path.dirname(h.record),'.registration.lock');fs.writeFileSync(lock,'');
|
|
105
|
+
const blocked=await run('register',['--plan',plan]);assert.notEqual(blocked.code,0);assert.ok(fs.existsSync(lock));
|
|
106
|
+
const blockedStart=await run('start',['--repo',h.dir,'--role',h.role,'--socket',h.source]);assert.notEqual(blockedStart.code,0);fs.unlinkSync(lock);
|
|
107
|
+
const successes=await Promise.all([run('register',['--plan',plan]),run('register',['--plan',plan])]);assert.equal(successes.filter(r=>r.code===0).length,1);
|
|
108
|
+
assert.equal(h.requests.filter(x=>['thread/start','turn/start','thread/settings/update'].includes(x.method)).length,0);
|
|
109
|
+
}finally{await h.close();}
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test('registered policy drift and uncertain claim never start work',async()=>{
|
|
113
|
+
const h=await fixture();try{
|
|
114
|
+
const plan=h.savePlan(await run('inspect-registration',h.args));assert.equal((await run('register',['--plan',plan])).code,0);
|
|
115
|
+
const args=['--repo',h.dir,'--role',h.role,'--record','unknown','--text','must not replay','--json'];
|
|
116
|
+
const entry=JSON.parse(fs.readFileSync(h.record));entry.deliveries={[crypto.createHash('sha256').update('unknown').digest('hex')]:{state:'pending',record:'unknown'}};fs.writeFileSync(h.record,JSON.stringify(entry));
|
|
117
|
+
let count=h.requests.filter(x=>x.method==='thread/resume').length;
|
|
118
|
+
assert.match((await run('deliver',args)).err,/outcome unknown/);assert.equal(h.requests.filter(x=>x.method==='thread/resume').length,count);
|
|
119
|
+
h.controls.badPolicy=true;
|
|
120
|
+
const drift=await run('deliver',args.map(x=>x==='unknown'?'new-record':x));assert.notEqual(drift.code,0);assert.match(drift.err,/policy mismatch/);
|
|
121
|
+
assert.equal(h.requests.filter(x=>x.method==='turn/start').length,0);assert.deepEqual(JSON.parse(fs.readFileSync(h.record)).deliveries,entry.deliveries);
|
|
122
|
+
}finally{await h.close();}
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
async function managed(h){const plan=h.savePlan(await run('inspect-registration',h.args));const r=await run('register',['--plan',plan]);assert.equal(r.code,0,r.err);const entry=JSON.parse(fs.readFileSync(h.record));entry.history=[{thread:'older-owned-thread',note:'original handover'}];entry.custom={preserved:true};entry.deliveries={[crypto.createHash('sha256').update('uncertain').digest('hex')]:{record:'uncertain',state:'pending'},[crypto.createHash('sha256').update('already').digest('hex')]:{record:'already',state:'delivered',turn:'previous-turn'}};fs.writeFileSync(h.record,JSON.stringify(entry));return entry;}
|
|
126
|
+
function migrationArgs(h){return ['--repo',h.dir,'--role',h.role,'--to-socket',h.target,'--authority','https://example.com/owner/approved-migration'];}
|
|
127
|
+
test('migrate original native endpoint preserving full history and all claims',async()=>{
|
|
128
|
+
const h=await fixture();try{
|
|
129
|
+
const entry=await managed(h);h.native.turns.push({id:'previous-two',status:'completed',items:[{id:'result-two',type:'agentMessage',text:'retain paginated second result'}]});
|
|
130
|
+
const plan=h.savePlan(await run('inspect-migration',migrationArgs(h)));const p=JSON.parse(fs.readFileSync(plan));assert.equal(p.historyCount,2);
|
|
131
|
+
const r=await run('migrate',['--plan',plan,'--json']);assert.equal(r.code,0,r.err);assert.equal(JSON.parse(r.out).state,'migrated');
|
|
132
|
+
const after=JSON.parse(fs.readFileSync(h.record));const {socket,endpointMigrations,...preserved}=after;const {socket:oldSocket,...original}=entry;assert.deepEqual(preserved,original);assert.equal(socket,h.target);assert.equal(endpointMigrations[0].plan,p.id);
|
|
133
|
+
const release=h.requests.findIndex(x=>x.method==='thread/unsubscribe');const target=h.requests.findIndex(x=>x.host==='target'&&x.method==='thread/resume');assert.ok(release>=0&&target>release);
|
|
134
|
+
assert.equal(h.native.loaded,'target');assert.equal(h.requests.filter(x=>['thread/start','turn/start','thread/settings/update'].includes(x.method)).length,0);
|
|
135
|
+
const args=['--repo',h.dir,'--role',h.role,'--record','already','--text','do not repeat','--json'];const duplicate=await run('deliver',args);assert.equal(duplicate.code,0,duplicate.err);assert.equal(JSON.parse(duplicate.out).turn,'previous-turn');
|
|
136
|
+
assert.match((await run('deliver',args.map(x=>x==='already'?'uncertain':x))).err,/outcome unknown/);
|
|
137
|
+
}finally{await h.close();}
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test('uncertain final journal commit reconciles without rewriting registry or repeating handoff',async()=>{
|
|
141
|
+
const h=await fixture();try{
|
|
142
|
+
await managed(h);const plan=h.savePlan(await run('inspect-migration',migrationArgs(h)));const p=JSON.parse(fs.readFileSync(plan));
|
|
143
|
+
assert.equal((await run('migrate',['--plan',plan])).code,0);
|
|
144
|
+
const journal=path.join(h.root,'codex-transitions',p.id+'.json'),entry=JSON.parse(fs.readFileSync(journal));
|
|
145
|
+
// Public persisted boundary: process died after the atomic registry commit
|
|
146
|
+
// and before its final journal write reached disk.
|
|
147
|
+
entry.state='unknown';entry.phase='verified';fs.writeFileSync(journal,JSON.stringify(entry));
|
|
148
|
+
const before=fs.readFileSync(h.record),releaseCount=h.requests.filter(x=>x.method==='thread/unsubscribe').length;
|
|
149
|
+
const reconciled=await run('migrate',['--plan',plan,'--reconcile','--json']);assert.equal(reconciled.code,0,reconciled.err);
|
|
150
|
+
assert.deepEqual(fs.readFileSync(h.record),before);assert.equal(h.requests.filter(x=>x.method==='thread/unsubscribe').length,releaseCount);
|
|
151
|
+
assert.equal(JSON.parse(fs.readFileSync(journal)).state,'committed');
|
|
152
|
+
}finally{await h.close();}
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test('migration refuses active work and input without consuming or creating intent',async()=>{
|
|
156
|
+
const h=await fixture();try{
|
|
157
|
+
await managed(h);const plan=h.savePlan(await run('inspect-migration',migrationArgs(h))),id=JSON.parse(fs.readFileSync(plan)).id;
|
|
158
|
+
const before=fs.readFileSync(h.record);
|
|
159
|
+
for(const flag of ['queued','goal','terminal']){
|
|
160
|
+
h.controls[flag]=true;const failed=await run('migrate',['--plan',plan]);assert.notEqual(failed.code,0,flag);h.controls[flag]=false;
|
|
161
|
+
assert.deepEqual(fs.readFileSync(h.record),before);assert.ok(!fs.existsSync(path.join(h.root,'codex-transitions',id+'.json')));
|
|
162
|
+
}
|
|
163
|
+
h.native.status='active';let failed=await run('migrate',['--plan',plan]);assert.match(failed.err,/active work/);h.native.status='idle';
|
|
164
|
+
h.native.turns.push({id:'running',status:'inProgress',items:[]});failed=await run('migrate',['--plan',plan]);assert.match(failed.err,/active work/);h.native.turns.pop();
|
|
165
|
+
assert.equal(h.requests.filter(x=>x.method==='thread/unsubscribe').length,0);assert.equal(h.requests.filter(x=>['turn/start','thread/start'].includes(x.method)).length,0);
|
|
166
|
+
}finally{await h.close();}
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
test('migration detects stale source and concurrent registry or role binding without overwrite',async()=>{
|
|
170
|
+
const h=await fixture();try{
|
|
171
|
+
await managed(h);const plan=h.savePlan(await run('inspect-migration',migrationArgs(h))),original=fs.readFileSync(h.record);
|
|
172
|
+
let changed=JSON.parse(original);changed.custom={external:'changed'};fs.writeFileSync(h.record,JSON.stringify(changed));
|
|
173
|
+
assert.match((await run('migrate',['--plan',plan])).err,/registry changed/);assert.deepEqual(JSON.parse(fs.readFileSync(h.record)).custom,changed.custom);fs.writeFileSync(h.record,original);
|
|
174
|
+
h.native.turns.push({id:'new-source-result',status:'completed',items:[]});assert.match((await run('migrate',['--plan',plan])).err,/history changed/);h.native.turns.pop();
|
|
175
|
+
const roleFile=path.join(h.root,'roles.json'),saved=fs.readFileSync(roleFile);
|
|
176
|
+
h.controls.beforeReply=(request,host)=>{if(host==='source'&&request.method==='thread/goal/get')fs.writeFileSync(roleFile,JSON.stringify({[h.dir]:'other-role'}));};
|
|
177
|
+
assert.match((await run('migrate',['--plan',plan])).err,/exact role/);fs.writeFileSync(roleFile,saved);
|
|
178
|
+
h.controls.beforeReply=(request,host)=>{if(host==='target'&&request.method==='thread/resume')fs.writeFileSync(h.record,JSON.stringify({...JSON.parse(original),custom:{external:'during-acquire'}}));};
|
|
179
|
+
assert.match((await run('migrate',['--plan',plan])).err,/registry changed/);assert.deepEqual(JSON.parse(fs.readFileSync(h.record)).custom,{external:'during-acquire'});
|
|
180
|
+
}finally{await h.close();}
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
test('migration failure journals preserve writer, identity, history and policy boundaries',async()=>{
|
|
184
|
+
for(const flag of ['retainWriter','missingHistory','targetBadPolicy','targetWrongId','targetWrongCwd']){
|
|
185
|
+
const h=await fixture();try{
|
|
186
|
+
await managed(h);const plan=h.savePlan(await run('inspect-migration',migrationArgs(h))),p=JSON.parse(fs.readFileSync(plan)),original=fs.readFileSync(h.record);
|
|
187
|
+
h.controls[flag]=true;const failed=await run('migrate',['--plan',plan]);assert.notEqual(failed.code,0,flag);assert.match(failed.err,/outcome unknown/);
|
|
188
|
+
assert.deepEqual(fs.readFileSync(h.record),original);assert.equal(JSON.parse(fs.readFileSync(path.join(h.root,'codex-transitions',p.id+'.json'))).state,'unknown');
|
|
189
|
+
const releaseCount=h.requests.filter(x=>x.method==='thread/unsubscribe').length,resumeCount=h.requests.filter(x=>x.method==='thread/resume').length;
|
|
190
|
+
assert.match((await run('migrate',['--plan',plan])).err,/explicitly reconcile/);
|
|
191
|
+
const status=await run('migration-status',['--plan',plan]);assert.equal(status.code,0,status.err);assert.equal(JSON.parse(status.out).state,'unknown');
|
|
192
|
+
assert.equal(h.requests.filter(x=>x.method==='thread/unsubscribe').length,releaseCount);assert.equal(h.requests.filter(x=>x.method==='thread/resume').length,resumeCount);
|
|
193
|
+
assert.equal(h.requests.filter(x=>['thread/start','turn/start','thread/settings/update'].includes(x.method)).length,0);
|
|
194
|
+
}finally{await h.close();}
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
test('unknown acquisition requires explicit loaded-target reconciliation and preserves new native work',async()=>{
|
|
199
|
+
const h=await fixture();try{
|
|
200
|
+
await managed(h);const plan=h.savePlan(await run('inspect-migration',migrationArgs(h))),before=JSON.parse(fs.readFileSync(h.record));
|
|
201
|
+
h.controls.dropAcquire=true;assert.match((await run('migrate',['--plan',plan])).err,/outcome unknown/);h.controls.dropAcquire=false;
|
|
202
|
+
const count=h.requests.filter(x=>x.method==='thread/resume').length,releaseCount=h.requests.filter(x=>x.method==='thread/unsubscribe').length;
|
|
203
|
+
h.native.loaded=null;assert.match((await run('migrate',['--plan',plan,'--reconcile'])).err,/not already loaded/);assert.equal(h.requests.filter(x=>x.method==='thread/resume').length,count);
|
|
204
|
+
h.native.loaded='target';h.native.status='active';h.native.turns.push({id:'native-work-after-uncertain-acquire',status:'inProgress',items:[{id:'preserved-active-tool',type:'commandExecution'}]});
|
|
205
|
+
const reconciled=await run('migrate',['--plan',plan,'--reconcile']);assert.equal(reconciled.code,0,reconciled.err);
|
|
206
|
+
assert.equal(h.native.status,'active');assert.equal(h.native.turns.at(-1).items[0].id,'preserved-active-tool');assert.equal(h.requests.filter(x=>x.method==='thread/unsubscribe').length,releaseCount);
|
|
207
|
+
const after=JSON.parse(fs.readFileSync(h.record));assert.deepEqual(after.deliveries,before.deliveries);
|
|
208
|
+
const repeated=await run('migrate',['--plan',plan]);assert.equal(repeated.code,0,repeated.err);assert.equal(JSON.parse(repeated.out).state,'already-migrated');
|
|
209
|
+
}finally{await h.close();}
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
test('equivalent built-in native profile representation migrates without relaxing effective policy',async()=>{
|
|
213
|
+
const h=await fixture();try{
|
|
214
|
+
h.native.policy.activePermissionProfile=null;await managed(h);
|
|
215
|
+
const plan=h.savePlan(await run('inspect-migration',migrationArgs(h)));
|
|
216
|
+
h.controls.beforeReply=(x,host)=>{if(host==='target'&&x.method==='thread/resume')h.native.policy.activePermissionProfile={id:':read-only',extends:null};};
|
|
217
|
+
const r=await run('migrate',['--plan',plan]);assert.equal(r.code,0,r.err);
|
|
218
|
+
const after=JSON.parse(fs.readFileSync(h.record));assert.equal(after.socket,h.target);assert.equal(after.nativePolicy.sandbox.type,'readOnly');assert.equal(after.nativePolicy.approvalPolicy,'on-request');
|
|
219
|
+
}finally{await h.close();}
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test('registered effective approval, roots and custom profiles remain exact',async()=>{
|
|
223
|
+
for(const change of [{approvalPolicy:'never'},{runtimeWorkspaceRoots:['/unapproved-root']},{activePermissionProfile:{id:'custom-review',extends:null}}]){
|
|
224
|
+
const h=await fixture();try{
|
|
225
|
+
await managed(h);const plan=h.savePlan(await run('inspect-migration',migrationArgs(h)));
|
|
226
|
+
h.controls.beforeReply=(x,host)=>{if(host==='target'&&x.method==='thread/resume')Object.assign(h.native.policy,change);};
|
|
227
|
+
const before=fs.readFileSync(h.record),r=await run('migrate',['--plan',plan]);assert.notEqual(r.code,0);assert.match(r.err,/policy mismatch/);assert.deepEqual(fs.readFileSync(h.record),before);
|
|
228
|
+
}finally{await h.close();}
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
test('migrated legacy default role enforces its audited native policy on subsequent work',async()=>{
|
|
233
|
+
const h=await fixture();try{
|
|
234
|
+
await managed(h);h.native.policy.sandbox={type:'workspaceWrite',writableRoots:[],networkAccess:false};
|
|
235
|
+
const entry=JSON.parse(fs.readFileSync(h.record));delete entry.registration;delete entry.nativePolicy;fs.writeFileSync(h.record,JSON.stringify(entry));
|
|
236
|
+
const plan=h.savePlan(await run('inspect-migration',migrationArgs(h)));assert.equal((await run('migrate',['--plan',plan])).code,0);
|
|
237
|
+
const before=fs.readFileSync(h.record);h.native.policy.approvalPolicy='never';
|
|
238
|
+
const delivered=await run('deliver',['--repo',h.dir,'--role',h.role,'--record','policy-must-hold','--text','must not run under changed policy']);
|
|
239
|
+
assert.notEqual(delivered.code,0);assert.match(delivered.err,/policy mismatch/);assert.equal(h.requests.filter(x=>x.method==='turn/start').length,0);assert.deepEqual(fs.readFileSync(h.record),before);
|
|
240
|
+
const recovered=await run('recover',['--repo',h.dir,'--role',h.role]);assert.notEqual(recovered.code,0);assert.match(recovered.err,/policy mismatch/);
|
|
241
|
+
h.native.policy.approvalPolicy='on-request';const recoveredOk=await run('recover',['--repo',h.dir,'--role',h.role,'--json']);assert.equal(recoveredOk.code,0,recoveredOk.err);assert.deepEqual(fs.readFileSync(h.record),before);
|
|
242
|
+
}finally{await h.close();}
|
|
243
|
+
});
|
|
@@ -5,7 +5,7 @@ from validation.common import ROOT, report
|
|
|
5
5
|
CODEX_HOST_EVIDENCE = {"hook_event_name": "PreToolUse", "transport": "stand-in WebSocket"}
|
|
6
6
|
|
|
7
7
|
def validate_codex_managed_host_scenario() -> int:
|
|
8
|
-
result = subprocess.run(["node", "--test", str(ROOT / "scripts/test_codex_host.js")], cwd=ROOT, capture_output=True, text=True, timeout=45)
|
|
8
|
+
result = subprocess.run(["node", "--test", str(ROOT / "scripts/test_codex_host.js"), str(ROOT / "scripts/test_codex_onboarding.js")], cwd=ROOT, capture_output=True, text=True, timeout=45)
|
|
9
9
|
if result.returncode:
|
|
10
10
|
report(result.stdout + result.stderr)
|
|
11
11
|
return 1
|
|
@@ -35,10 +35,10 @@ os.environ["KEEL_UPDATE_CLAUDE"] = str(Path(tempfile.gettempdir()) / "keel-suite
|
|
|
35
35
|
os.environ["KEEL_UPDATE_CODEX"] = str(Path(tempfile.gettempdir()) / "keel-suite-has-no-codex")
|
|
36
36
|
|
|
37
37
|
|
|
38
|
-
PACKAGE_VERSION = "5.
|
|
38
|
+
PACKAGE_VERSION = "5.231.0"
|
|
39
39
|
|
|
40
40
|
|
|
41
|
-
PROTOCOL_VERSION = "5.
|
|
41
|
+
PROTOCOL_VERSION = "5.231.0"
|
|
42
42
|
|
|
43
43
|
|
|
44
44
|
LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
|
package/src/core/codex-host.js
CHANGED
|
@@ -119,19 +119,22 @@ function connect(socketPath, timeout = 5000) {
|
|
|
119
119
|
}
|
|
120
120
|
|
|
121
121
|
async function run(args) {
|
|
122
|
+
const onboarding = require("./codex-onboarding");
|
|
123
|
+
if (onboarding.actions.includes(args[0])) return onboarding.run(args, {connect});
|
|
122
124
|
let client;
|
|
123
125
|
let reservation;
|
|
124
126
|
let roleLock;
|
|
127
|
+
let registrationLock;
|
|
125
128
|
try {
|
|
126
129
|
const action = args.shift();
|
|
127
|
-
if (!["status", "start", "deliver", "handover", "drain"].includes(action)) throw Error("Usage: keel codex status|start|deliver|handover|drain [--socket path] [--role name] [--repo path] [--thread id] [--timeout ms] [--json]");
|
|
130
|
+
if (!["status", "start", "deliver", "handover", "drain", "recover"].includes(action)) throw Error("Usage: keel codex status|start|deliver|handover|drain|recover [--socket path] [--role name] [--repo path] [--thread id] [--timeout ms] [--json]");
|
|
128
131
|
const options = {socket: path.join(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"), "app-server-control/app-server-control.sock"), timeout: 5000, repo: process.cwd()};
|
|
129
132
|
let explicitSocket = false;
|
|
130
133
|
let explicitTimeout = false;
|
|
131
134
|
while (args.length) {
|
|
132
135
|
const flag = args.shift();
|
|
133
136
|
if (flag === "--json") options.json = true;
|
|
134
|
-
else if (["--socket", "--thread", "--timeout", "--role", "--repo", "--record", "--text", "--note"].includes(flag)) {
|
|
137
|
+
else if (["--socket", "--thread", "--timeout", "--role", "--repo", "--record", "--text", "--note", "--approvals-reviewer"].includes(flag)) {
|
|
135
138
|
const value = args.shift();
|
|
136
139
|
if (!value || value.startsWith("--")) throw Error(`${flag} needs a value`);
|
|
137
140
|
options[flag.slice(2)] = value;
|
|
@@ -139,6 +142,9 @@ async function run(args) {
|
|
|
139
142
|
if (flag === "--timeout") explicitTimeout = true;
|
|
140
143
|
} else throw Error(`Unknown argument ${flag}`);
|
|
141
144
|
}
|
|
145
|
+
const requestedReviewer = options["approvals-reviewer"];
|
|
146
|
+
if (requestedReviewer && !["user", "auto_review"].includes(requestedReviewer)) throw Error("approvals-reviewer must be user or auto_review");
|
|
147
|
+
if (requestedReviewer && action !== "start") throw Error("--approvals-reviewer is only accepted by start");
|
|
142
148
|
const ms = Number(options.timeout);
|
|
143
149
|
if (!Number.isInteger(ms) || ms < 50 || ms > 60000) throw Error("timeout must be 50–60000 milliseconds");
|
|
144
150
|
const fs = require("node:fs");
|
|
@@ -167,7 +173,7 @@ async function run(args) {
|
|
|
167
173
|
}
|
|
168
174
|
}
|
|
169
175
|
if (action === "start" && !options.role) throw Error("start needs --role");
|
|
170
|
-
if (["deliver", "handover"].includes(action)) {
|
|
176
|
+
if (["deliver", "handover", "recover"].includes(action)) {
|
|
171
177
|
if (!recorded) throw Error("operation needs a managed --role");
|
|
172
178
|
const candidateLock = `${file}.lock`;
|
|
173
179
|
const fd = fs.openSync(candidateLock, "wx"); fs.closeSync(fd);
|
|
@@ -179,35 +185,70 @@ async function run(args) {
|
|
|
179
185
|
if (action === "deliver" && (!options.record || !options.text)) throw Error("deliver needs --record and --text");
|
|
180
186
|
if (action === "handover" && !options.note) throw Error("handover needs --note");
|
|
181
187
|
}
|
|
188
|
+
if (action === "start") {
|
|
189
|
+
const directory = path.dirname(file); fs.mkdirSync(directory, {recursive: true});
|
|
190
|
+
const candidate = path.join(directory, ".registration.lock");
|
|
191
|
+
const fd = fs.openSync(candidate, "wx"); fs.closeSync(fd); registrationLock = candidate;
|
|
192
|
+
if (fs.existsSync(file)) throw Error("managed role already exists or creation outcome unknown");
|
|
193
|
+
}
|
|
194
|
+
if (action === "handover" && recorded?.registration) throw Error("registered frontend handover requires separate successor authorization; no replacement started");
|
|
195
|
+
const savedPolicy = onboarding.policyFor(recorded);
|
|
182
196
|
client = await connect(options.socket, ms);
|
|
183
|
-
const host = await client.call("initialize", {clientInfo: {name: "keel", version: "1"}});
|
|
197
|
+
const host = await client.call("initialize", {clientInfo: {name: "keel", version: "1"}, ...(requestedReviewer || recorded?.approvalsReviewer || savedPolicy ? {capabilities: {experimentalApi: true}} : {})});
|
|
184
198
|
if (!host || typeof host.userAgent !== "string" || !host.userAgent) throw Error("Codex host returned no initialization identity");
|
|
185
199
|
client.notify("initialized");
|
|
186
200
|
const result = {socket: options.socket, host};
|
|
187
|
-
|
|
201
|
+
function verifyReviewerPolicy(reply, reviewer) {
|
|
202
|
+
if (!reviewer) return;
|
|
203
|
+
if (reply.approvalsReviewer !== reviewer) throw Error("Codex thread reviewer mismatch; original identity retained");
|
|
204
|
+
if (reply.approvalPolicy !== "on-request") throw Error("Codex thread approval policy mismatch; original identity retained");
|
|
205
|
+
if (reply.sandbox?.type !== "workspaceWrite") throw Error("Codex thread sandbox mismatch; original identity retained");
|
|
206
|
+
}
|
|
207
|
+
async function initializeThread(thread, reviewer) {
|
|
188
208
|
// Native metadata writes materialize fresh persistent threads without a
|
|
189
209
|
// model turn. Blank thread/start alone has no durable rollout yet.
|
|
190
210
|
await client.call("thread/name/set", {threadId: thread.id, name: options.role});
|
|
211
|
+
if (reviewer) await client.call("thread/settings/update", {threadId: thread.id, approvalsReviewer: reviewer, approvalPolicy: "on-request"});
|
|
191
212
|
const verified = (await client.call("thread/read", {threadId: thread.id, includeTurns: false})).thread;
|
|
192
213
|
if (!verified || verified.id !== thread.id || verified.cwd !== where.worktree) {
|
|
193
214
|
throw Error("initialized managed role identity mismatch");
|
|
194
215
|
}
|
|
195
216
|
}
|
|
196
217
|
if (action === "start") {
|
|
218
|
+
const reviewerPolicy = requestedReviewer ? {approvalsReviewer: requestedReviewer} : {};
|
|
197
219
|
fs.mkdirSync(path.dirname(file), {recursive: true});
|
|
198
220
|
const fd = fs.openSync(file, "wx");
|
|
199
|
-
fs.writeFileSync(fd, JSON.stringify({state: "creation-pending", role: options.role, worktree: where.worktree, socket: options.socket}));
|
|
221
|
+
fs.writeFileSync(fd, JSON.stringify({state: "creation-pending", role: options.role, worktree: where.worktree, socket: options.socket, ...reviewerPolicy}));
|
|
200
222
|
fs.closeSync(fd);
|
|
201
223
|
reservation = file;
|
|
202
|
-
const started = await client.call("thread/start", {cwd: where.worktree, sandbox: "workspace-write", approvalPolicy: "on-request", serviceName: "keel"});
|
|
224
|
+
const started = await client.call("thread/start", {cwd: where.worktree, sandbox: "workspace-write", approvalPolicy: "on-request", serviceName: "keel", ...reviewerPolicy});
|
|
203
225
|
const thread = started.thread;
|
|
204
226
|
if (!thread || !thread.id || thread.cwd !== where.worktree) throw Error("Codex created thread with unexpected identity");
|
|
205
|
-
store.writeJsonAtomic(where, file, {state: "creation-pending", role: options.role, thread: thread.id, worktree: where.worktree, socket: options.socket});
|
|
206
|
-
|
|
207
|
-
|
|
227
|
+
store.writeJsonAtomic(where, file, {state: "creation-pending", role: options.role, thread: thread.id, worktree: where.worktree, socket: options.socket, ...reviewerPolicy});
|
|
228
|
+
verifyReviewerPolicy(started, requestedReviewer);
|
|
229
|
+
await initializeThread(thread, requestedReviewer);
|
|
230
|
+
const entry = {state: "managed", role: options.role, thread: thread.id, worktree: where.worktree, socket: options.socket, ...reviewerPolicy};
|
|
208
231
|
store.writeJsonAtomic(where, file, entry);
|
|
209
232
|
store.setRole(where, options.role);
|
|
210
233
|
Object.assign(result, entry);
|
|
234
|
+
} else if (action === "recover") {
|
|
235
|
+
const original = (await client.call("thread/read", {threadId: recorded.thread, includeTurns: false})).thread;
|
|
236
|
+
if (!original || original.id !== recorded.thread) throw Error("managed role identity mismatch; no recovery attempted");
|
|
237
|
+
if (!original.status || !["idle", "active", "notLoaded"].includes(original.status.type)) throw Error("managed role state is not verified; no recovery attempted");
|
|
238
|
+
if (original.status.type === "active") {
|
|
239
|
+
Object.assign(result, {state: "waiting", thread: recorded.thread});
|
|
240
|
+
} else {
|
|
241
|
+
// Native writer ownership decides whether the original id can resume.
|
|
242
|
+
// Restore only the recorded execution cwd; never rewrite role claims.
|
|
243
|
+
const resumed = await client.call("thread/resume", {threadId: recorded.thread, cwd: recorded.worktree, ...(savedPolicy ? (savedPolicy.runtimeWorkspaceRoots !== undefined ? {runtimeWorkspaceRoots: savedPolicy.runtimeWorkspaceRoots} : {}) : {runtimeWorkspaceRoots: [recorded.worktree]}), serviceName: "keel", ...(!savedPolicy && recorded.approvalsReviewer ? {approvalsReviewer: recorded.approvalsReviewer} : {})}, explicitTimeout ? ms : Math.max(ms, 15000));
|
|
244
|
+
if (!resumed.thread || resumed.thread.id !== recorded.thread || resumed.thread.cwd !== recorded.worktree) throw Error("recovered managed role identity mismatch; original registry retained");
|
|
245
|
+
if (savedPolicy) onboarding.verifyPolicy(resumed, savedPolicy);
|
|
246
|
+
else if (resumed.approvalPolicy !== "on-request") throw Error("recovered thread approval policy mismatch; original registry retained");
|
|
247
|
+
if (!savedPolicy && resumed.sandbox?.type !== "workspaceWrite") throw Error("recovered thread sandbox mismatch; original registry retained");
|
|
248
|
+
if (recorded.approvalsReviewer && resumed.approvalsReviewer !== recorded.approvalsReviewer) throw Error("recovered thread reviewer mismatch; original registry retained");
|
|
249
|
+
if (resumed.thread.status?.type !== "idle") throw Error("recovered thread is not verified idle; original registry retained");
|
|
250
|
+
Object.assign(result, {state: "recovered", thread: recorded.thread, worktree: recorded.worktree});
|
|
251
|
+
}
|
|
211
252
|
} else if (["deliver", "handover"].includes(action)) {
|
|
212
253
|
let thread = (await client.call("thread/read", {threadId: recorded.thread, includeTurns: false})).thread;
|
|
213
254
|
const owned = value => value && value.id === recorded.thread && value.cwd === recorded.worktree;
|
|
@@ -221,12 +262,18 @@ async function run(args) {
|
|
|
221
262
|
}
|
|
222
263
|
Object.assign(result, {state: "already-delivered", turn: claims[key].turn});
|
|
223
264
|
} else {
|
|
224
|
-
if (action === "deliver" && thread.status && thread.status.type === "notLoaded") {
|
|
265
|
+
if (action === "deliver" && thread.status && (thread.status.type === "notLoaded" || ((recorded.approvalsReviewer || savedPolicy) && thread.status.type === "idle"))) {
|
|
225
266
|
// Only this recorded owned identity may be loaded. Keep this same
|
|
226
267
|
// connection alive through the subsequent turn/start and preserve
|
|
227
|
-
//
|
|
228
|
-
|
|
268
|
+
// saved sandbox/approval settings. An explicitly chosen reviewer
|
|
269
|
+
// belongs to the managed role and follows its later deliveries.
|
|
270
|
+
const resumed = await client.call("thread/resume", {threadId: recorded.thread, ...(!savedPolicy ? {serviceName: "keel", ...(recorded.approvalsReviewer ? {approvalsReviewer: recorded.approvalsReviewer} : {})} : {})}, explicitTimeout ? ms : Math.max(ms, 15000));
|
|
271
|
+
thread = resumed.thread;
|
|
229
272
|
if (!owned(thread)) throw Error("resumed managed role identity mismatch");
|
|
273
|
+
if (thread.status?.type === "idle") {
|
|
274
|
+
if (savedPolicy) onboarding.verifyPolicy(resumed, savedPolicy);
|
|
275
|
+
else verifyReviewerPolicy(resumed, recorded.approvalsReviewer);
|
|
276
|
+
}
|
|
230
277
|
}
|
|
231
278
|
if (!thread.status || !["idle", "active"].includes(thread.status.type)) {
|
|
232
279
|
throw Error("managed role state is not verified idle or active; no work started");
|
|
@@ -237,7 +284,7 @@ async function run(args) {
|
|
|
237
284
|
claims[key] = {record: options.record, state: "pending"};
|
|
238
285
|
recorded.deliveries = claims;
|
|
239
286
|
store.writeJsonAtomic(where, file, recorded);
|
|
240
|
-
const turn = (await client.call("turn/start", {threadId: recorded.thread, input: [{type: "text", text: (recorded.note ? `Handover note (context only):\n${recorded.note}\n\n` : "") + options.text}]})).turn;
|
|
287
|
+
const turn = (await client.call("turn/start", {threadId: recorded.thread, ...(!savedPolicy && recorded.approvalsReviewer ? {approvalsReviewer: recorded.approvalsReviewer} : {}), input: [{type: "text", text: (recorded.note ? `Handover note (context only):\n${recorded.note}\n\n` : "") + options.text}]})).turn;
|
|
241
288
|
if (!turn || !turn.id) throw Error("Codex returned no turn identity; claim retained");
|
|
242
289
|
claims[key] = {record: options.record, state: "delivered", turn: turn.id};
|
|
243
290
|
store.writeJsonAtomic(where, file, recorded);
|
|
@@ -246,11 +293,13 @@ async function run(args) {
|
|
|
246
293
|
if (recorded.handover) throw Error("handover outcome unknown; no successor started");
|
|
247
294
|
recorded.handover = {state: "pending", note: options.note};
|
|
248
295
|
store.writeJsonAtomic(where, file, recorded);
|
|
249
|
-
const
|
|
296
|
+
const successor = await client.call("thread/start", {cwd: recorded.worktree, sandbox: "workspace-write", approvalPolicy: "on-request", serviceName: "keel", ...(recorded.approvalsReviewer ? {approvalsReviewer: recorded.approvalsReviewer} : {})});
|
|
297
|
+
const next = successor.thread;
|
|
250
298
|
if (!next || !next.id || next.cwd !== recorded.worktree) throw Error("successor identity mismatch; handover retained");
|
|
251
299
|
recorded.handover.thread = next.id;
|
|
252
300
|
store.writeJsonAtomic(where, file, recorded);
|
|
253
|
-
|
|
301
|
+
verifyReviewerPolicy(successor, recorded.approvalsReviewer);
|
|
302
|
+
await initializeThread(next, recorded.approvalsReviewer);
|
|
254
303
|
const history = [...(recorded.history || []), {thread: recorded.thread, note: options.note}];
|
|
255
304
|
delete recorded.handover;
|
|
256
305
|
Object.assign(recorded, {thread: next.id, history, note: options.note});
|
|
@@ -270,6 +319,7 @@ async function run(args) {
|
|
|
270
319
|
} finally {
|
|
271
320
|
if (client) client.close();
|
|
272
321
|
if (roleLock) require("node:fs").rmSync(roleLock, {force: true});
|
|
322
|
+
if (registrationLock) require("node:fs").rmSync(registrationLock, {force: true});
|
|
273
323
|
}
|
|
274
324
|
}
|
|
275
325
|
// Use the existing mailbox addressing rules and parking decisions. Calling the
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
const crypto = require('node:crypto');
|
|
5
|
+
const store = require('./chat/store');
|
|
6
|
+
const actions = ['inspect-registration', 'register', 'inspect-migration', 'migrate', 'migration-status'];
|
|
7
|
+
const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
|
|
8
|
+
const digest = value => crypto.createHash('sha256').update(typeof value === 'string' || Buffer.isBuffer(value) ? value : JSON.stringify(canonical(value))).digest('hex');
|
|
9
|
+
const same = (a, b) => digest(a) === digest(b);
|
|
10
|
+
function policyOf(reply) {
|
|
11
|
+
if (!reply.sandbox?.type || !reply.approvalPolicy || !['user', 'auto_review'].includes(reply.approvalsReviewer)) throw Error('native effective policy unavailable');
|
|
12
|
+
const result = {};
|
|
13
|
+
for (const key of ['approvalPolicy', 'approvalsReviewer', 'sandbox', 'runtimeWorkspaceRoots', 'activePermissionProfile']) {
|
|
14
|
+
if (key === 'activePermissionProfile') {
|
|
15
|
+
const profile = reply[key];
|
|
16
|
+
const builtin = {readOnly: ':read-only', workspaceWrite: ':workspace-write'}[reply.sandbox.type];
|
|
17
|
+
// Native cold resume may attach built-in provenance to an unchanged
|
|
18
|
+
// legacy policy. Custom profiles and every effective field stay exact.
|
|
19
|
+
if (profile == null || (builtin && profile.id === builtin && profile.extends == null)) continue;
|
|
20
|
+
}
|
|
21
|
+
if (reply[key] !== undefined) result[key] = reply[key];
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
function policyFor(record) { return record?.nativePolicy || record?.endpointMigrations?.at(-1)?.nativePolicy; }
|
|
26
|
+
function verifyPolicy(reply, expected) {
|
|
27
|
+
if (!same(policyOf(reply), expected)) throw Error('native effective policy mismatch; no policy override attempted');
|
|
28
|
+
}
|
|
29
|
+
function verifyThread(thread, plan) {
|
|
30
|
+
if (!thread || thread.id !== plan.thread || thread.cwd !== plan.worktree) throw Error('original thread identity or worktree mismatch');
|
|
31
|
+
if (!['idle', 'active', 'notLoaded'].includes(thread.status?.type)) throw Error('original native thread state is unverified');
|
|
32
|
+
}
|
|
33
|
+
function acquire(file, locks) {
|
|
34
|
+
fs.mkdirSync(path.dirname(file), {recursive: true});
|
|
35
|
+
const fd = fs.openSync(file, 'wx'); fs.closeSync(fd); locks.push(file);
|
|
36
|
+
}
|
|
37
|
+
function binding(where, role) {
|
|
38
|
+
store.checkName(role, 'Role');
|
|
39
|
+
if (role === 'keel') throw Error('Role name keel is reserved');
|
|
40
|
+
if (store.canonicalRole(where.root, role) !== role) throw Error('Role was renamed; use its current canonical name');
|
|
41
|
+
const roles = JSON.parse(fs.readFileSync(path.join(where.root, 'roles.json'), 'utf8'));
|
|
42
|
+
if (roles[where.worktree] !== role) throw Error('worktree must already be bound to this exact role');
|
|
43
|
+
if (Object.entries(roles).some(([worktree, name]) => name === role && worktree !== where.worktree)) throw Error('role is bound to another worktree');
|
|
44
|
+
}
|
|
45
|
+
function unique(where, role, thread, registering) {
|
|
46
|
+
const directory = path.join(where.root, 'codex-roles');
|
|
47
|
+
if (!fs.existsSync(directory)) return;
|
|
48
|
+
for (const name of fs.readdirSync(directory).filter(name => name.endsWith('.json'))) {
|
|
49
|
+
const value = JSON.parse(fs.readFileSync(path.join(directory, name), 'utf8'));
|
|
50
|
+
if (name === role + '.json') {
|
|
51
|
+
if (registering) throw Error('managed role already exists or creation outcome unknown');
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (value.thread === thread || value.handover?.thread === thread || value.history?.some(item => item.thread === thread)) throw Error('original thread already belongs to another managed role');
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function loadPlan(file) {
|
|
58
|
+
const plan = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
59
|
+
const {id, ...body} = plan;
|
|
60
|
+
if (plan.schema !== 'keel-codex-onboarding/v1' || !id || digest(body) !== id) throw Error('invalid or tampered onboarding plan');
|
|
61
|
+
return plan;
|
|
62
|
+
}
|
|
63
|
+
function savePlan(body) { return {...body, id: digest(body)}; }
|
|
64
|
+
async function history(client, thread) {
|
|
65
|
+
const turns = [], seen = new Set(); let cursor;
|
|
66
|
+
do {
|
|
67
|
+
const reply = await client.call('thread/turns/list', {threadId: thread, sortDirection: 'asc', itemsView: 'full', limit: 50, ...(cursor ? {cursor} : {})});
|
|
68
|
+
if (!Array.isArray(reply.data)) throw Error('native full history unavailable');
|
|
69
|
+
turns.push(...reply.data);
|
|
70
|
+
cursor = reply.nextCursor;
|
|
71
|
+
if (cursor && (typeof cursor !== 'string' || seen.has(cursor))) throw Error('native history cursor did not advance');
|
|
72
|
+
if (cursor) seen.add(cursor);
|
|
73
|
+
} while (cursor);
|
|
74
|
+
return turns;
|
|
75
|
+
}
|
|
76
|
+
async function run(args, {connect}) {
|
|
77
|
+
const clients = [], locks = [];
|
|
78
|
+
try {
|
|
79
|
+
const action = args.shift(), options = {timeout: 15000};
|
|
80
|
+
while (args.length) {
|
|
81
|
+
const flag = args.shift();
|
|
82
|
+
if (flag === '--json') continue;
|
|
83
|
+
if (flag === '--reconcile') {options.reconcile = true; continue;}
|
|
84
|
+
if (!['--repo', '--role', '--thread', '--socket', '--authority', '--plan', '--timeout', '--to-socket'].includes(flag)) throw Error(`Unknown argument ${flag}`);
|
|
85
|
+
const value = args.shift();
|
|
86
|
+
if (!value || value.startsWith('--')) throw Error(`${flag} needs a value`);
|
|
87
|
+
if (options[flag.slice(2)] !== undefined && flag !== '--timeout') throw Error(`duplicate ${flag}`);
|
|
88
|
+
options[flag.slice(2)] = value;
|
|
89
|
+
}
|
|
90
|
+
const timeout = Number(options.timeout);
|
|
91
|
+
if (!Number.isInteger(timeout) || timeout < 50 || timeout > 60000) throw Error('timeout must be 50–60000 milliseconds');
|
|
92
|
+
if (['inspect-migration', 'migrate', 'migration-status'].includes(action)) return await migration(action, options, {connect, timeout, clients, locks});
|
|
93
|
+
if (options.reconcile || options['to-socket']) throw Error('migration-only option used for registration');
|
|
94
|
+
let plan, where;
|
|
95
|
+
const applying = action === 'register';
|
|
96
|
+
if (applying) {
|
|
97
|
+
if (!options.plan) throw Error('register needs --plan');
|
|
98
|
+
if (['repo','role','thread','socket','authority'].some(key => options[key])) throw Error('apply takes the exact plan; tuple overrides are not accepted');
|
|
99
|
+
plan = loadPlan(options.plan);
|
|
100
|
+
if (plan.action !== 'registration') throw Error('plan action mismatch');
|
|
101
|
+
where = store.requireLocation(plan.worktree);
|
|
102
|
+
if (where.root !== plan.root || where.worktree !== plan.worktree) throw Error('plan repository identity mismatch');
|
|
103
|
+
} else {
|
|
104
|
+
if (options.plan || ['repo','role','thread','socket','authority'].some(key => !options[key])) throw Error('inspect-registration needs explicit --repo --role --thread --socket --authority');
|
|
105
|
+
if (!path.isAbsolute(options.socket)) throw Error('native socket must be an absolute path');
|
|
106
|
+
where = store.requireLocation(path.resolve(options.repo));
|
|
107
|
+
plan = {schema: 'keel-codex-onboarding/v1', action: 'registration', root: where.root, worktree: where.worktree, role: options.role, thread: options.thread, socket: options.socket, authority: options.authority};
|
|
108
|
+
}
|
|
109
|
+
acquire(path.join(where.root, 'codex-roles', '.registration.lock'), locks);
|
|
110
|
+
binding(where, plan.role);
|
|
111
|
+
unique(where, plan.role, plan.thread, true);
|
|
112
|
+
const file = path.join(where.root, 'codex-roles', plan.role + '.json');
|
|
113
|
+
acquire(file + '.lock', locks);
|
|
114
|
+
const client = await connect(plan.socket, timeout); clients.push(client);
|
|
115
|
+
const host = await client.call('initialize', {clientInfo: {name: 'keel-onboarding', version: '1'}, capabilities: {experimentalApi: true}});
|
|
116
|
+
if (!host?.userAgent) throw Error('Codex host returned no initialization identity');
|
|
117
|
+
client.notify('initialized');
|
|
118
|
+
const before = (await client.call('thread/read', {threadId: plan.thread, includeTurns: false})).thread;
|
|
119
|
+
verifyThread(before, plan);
|
|
120
|
+
// Rejoin the exact native context. No settings, cwd or permission overrides.
|
|
121
|
+
const native = await client.call('thread/resume', {threadId: plan.thread});
|
|
122
|
+
verifyThread(native.thread, plan);
|
|
123
|
+
if (!['idle', 'active'].includes(native.thread.status.type)) throw Error('original thread is not loaded after native rejoin');
|
|
124
|
+
const policy = policyOf(native);
|
|
125
|
+
if (applying) verifyPolicy(native, plan.nativePolicy);
|
|
126
|
+
const turns = await history(client, plan.thread);
|
|
127
|
+
if (!applying) {
|
|
128
|
+
const prepared = savePlan({...plan, nativePolicy: policy, historyDigest: digest(turns), historyCount: turns.length});
|
|
129
|
+
process.stdout.write(JSON.stringify(prepared) + '\n');
|
|
130
|
+
} else {
|
|
131
|
+
binding(where, plan.role); unique(where, plan.role, plan.thread, true);
|
|
132
|
+
const entry = {state: 'managed', role: plan.role, thread: plan.thread, worktree: plan.worktree, socket: plan.socket, nativePolicy: policy, registration: {plan: plan.id, authority: plan.authority, historyDigest: plan.historyDigest, historyCount: plan.historyCount}};
|
|
133
|
+
// Hard link is atomic no-overwrite; a failed/competing write cannot turn
|
|
134
|
+
// a partial file into a managed record. Existing worktree binding stays.
|
|
135
|
+
const temporary = file + '.' + crypto.randomBytes(8).toString('hex') + '.tmp';
|
|
136
|
+
try {fs.writeFileSync(temporary, JSON.stringify(entry, null, 2) + '\n', {flag: 'wx', mode: 0o600}); fs.linkSync(temporary, file);}
|
|
137
|
+
finally {fs.rmSync(temporary, {force: true});}
|
|
138
|
+
process.stdout.write(JSON.stringify({state: 'registered', role: plan.role, thread: plan.thread, socket: plan.socket, plan: plan.id}) + '\n');
|
|
139
|
+
}
|
|
140
|
+
return 0;
|
|
141
|
+
} catch (error) {process.stderr.write(`keel codex: ${error.message}\n`); return 1;}
|
|
142
|
+
finally {clients.forEach(client => client.close()); locks.reverse().forEach(file => fs.rmSync(file, {force: true}));}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function openHost(socket, {connect, timeout, clients}) {
|
|
146
|
+
const client = await connect(socket, timeout); clients.push(client);
|
|
147
|
+
const host = await client.call('initialize', {clientInfo: {name: 'keel-onboarding', version: '1'}, capabilities: {experimentalApi: true}});
|
|
148
|
+
if (!host?.userAgent) throw Error('Codex host returned no initialization identity');
|
|
149
|
+
client.notify('initialized'); return client;
|
|
150
|
+
}
|
|
151
|
+
async function quiescent(client, plan, thread, turns) {
|
|
152
|
+
if (thread.status.type !== 'idle' || turns.some(turn => turn.status === 'inProgress')) throw Error('source has active work; no handoff attempted');
|
|
153
|
+
const [queue, goal, terminals] = await Promise.all([
|
|
154
|
+
client.call('thread/queue/list', {threadId: plan.thread}),
|
|
155
|
+
client.call('thread/goal/get', {threadId: plan.thread}),
|
|
156
|
+
client.call('thread/backgroundTerminals/list', {threadId: plan.thread}),
|
|
157
|
+
]);
|
|
158
|
+
if (!Array.isArray(queue.data) || queue.data.length || queue.nextCursor) throw Error('source queue is not verified empty; input retained');
|
|
159
|
+
if (!Object.hasOwn(goal, 'goal') || goal.goal !== null) throw Error('source Goal is not verified absent; Goal retained');
|
|
160
|
+
if (!Array.isArray(terminals.data) || terminals.data.length || terminals.nextCursor) throw Error('source background tools are not verified absent; tools retained');
|
|
161
|
+
}
|
|
162
|
+
async function inspectSource(client, plan, recorded) {
|
|
163
|
+
const before = (await client.call('thread/read', {threadId: plan.thread, includeTurns: false})).thread;
|
|
164
|
+
verifyThread(before, plan);
|
|
165
|
+
if (before.status.type === 'active') throw Error('source has active work; no handoff attempted');
|
|
166
|
+
const native = await client.call('thread/resume', {threadId: plan.thread});
|
|
167
|
+
verifyThread(native.thread, plan);
|
|
168
|
+
const nativePolicy = policyOf(native);
|
|
169
|
+
if (policyFor(recorded)) verifyPolicy(native, policyFor(recorded));
|
|
170
|
+
else {
|
|
171
|
+
if (nativePolicy.approvalPolicy !== 'on-request' || nativePolicy.sandbox.type !== 'workspaceWrite') throw Error('legacy managed role policy mismatch; no handoff attempted');
|
|
172
|
+
if (recorded.approvalsReviewer && nativePolicy.approvalsReviewer !== recorded.approvalsReviewer) throw Error('legacy managed role reviewer mismatch; no handoff attempted');
|
|
173
|
+
}
|
|
174
|
+
const turns = await history(client, plan.thread);
|
|
175
|
+
await quiescent(client, plan, native.thread, turns);
|
|
176
|
+
return {nativePolicy, historyDigest: digest(turns), historyCount: turns.length};
|
|
177
|
+
}
|
|
178
|
+
async function migration(action, options, context) {
|
|
179
|
+
const {clients, locks} = context;
|
|
180
|
+
const applying = action !== 'inspect-migration';
|
|
181
|
+
let where, plan;
|
|
182
|
+
if (applying) {
|
|
183
|
+
if (!options.plan) throw Error(`${action} needs --plan`);
|
|
184
|
+
if (['repo', 'role', 'thread', 'socket', 'authority', 'to-socket'].some(key => options[key])) throw Error('apply takes the exact plan; tuple overrides are not accepted');
|
|
185
|
+
if (options.reconcile && action !== 'migrate') throw Error('--reconcile is only accepted by migrate');
|
|
186
|
+
plan = loadPlan(options.plan);
|
|
187
|
+
if (plan.action !== 'migration') throw Error('plan action mismatch');
|
|
188
|
+
where = store.requireLocation(plan.worktree);
|
|
189
|
+
if (where.root !== plan.root || where.worktree !== plan.worktree) throw Error('plan repository identity mismatch');
|
|
190
|
+
} else {
|
|
191
|
+
if (options.plan || options.reconcile || options.thread || options.socket || ['repo', 'role', 'to-socket', 'authority'].some(key => !options[key])) throw Error('inspect-migration needs explicit --repo --role --to-socket --authority');
|
|
192
|
+
if (!path.isAbsolute(options['to-socket'])) throw Error('native target socket must be an absolute path');
|
|
193
|
+
where = store.requireLocation(path.resolve(options.repo));
|
|
194
|
+
plan = {schema: 'keel-codex-onboarding/v1', action: 'migration', root: where.root, worktree: where.worktree, role: options.role, toSocket: options['to-socket'], authority: options.authority};
|
|
195
|
+
}
|
|
196
|
+
binding(where, plan.role);
|
|
197
|
+
const file = path.join(where.root, 'codex-roles', plan.role + '.json');
|
|
198
|
+
const journalFile = applying ? path.join(where.root, 'codex-transitions', plan.id + '.json') : null;
|
|
199
|
+
if (action === 'migration-status') {
|
|
200
|
+
const journal = fs.existsSync(journalFile) ? JSON.parse(fs.readFileSync(journalFile, 'utf8')) : null;
|
|
201
|
+
const registry = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
202
|
+
const observed = {};
|
|
203
|
+
for (const [name, socket] of [['source', plan.fromSocket], ['target', plan.toSocket]]) {
|
|
204
|
+
try {
|
|
205
|
+
const client = await openHost(socket, context);
|
|
206
|
+
const thread = (await client.call('thread/read', {threadId: plan.thread, includeTurns: false})).thread;
|
|
207
|
+
verifyThread(thread, plan); observed[name] = {state: thread.status.type};
|
|
208
|
+
} catch (error) {observed[name] = {error: error.message};}
|
|
209
|
+
}
|
|
210
|
+
process.stdout.write(JSON.stringify({state: journal?.state || 'not-started', phase: journal?.phase || null, registrySocket: registry.socket, registryMatchesSourceSnapshot: digest(fs.readFileSync(file)) === plan.registryDigest, observed}) + '\n');
|
|
211
|
+
return 0;
|
|
212
|
+
}
|
|
213
|
+
acquire(path.join(where.root, 'codex-roles', '.registration.lock'), locks);
|
|
214
|
+
acquire(file + '.lock', locks);
|
|
215
|
+
binding(where, plan.role);
|
|
216
|
+
const bytes = fs.readFileSync(file), recorded = JSON.parse(bytes);
|
|
217
|
+
if (recorded.state !== 'managed' || recorded.role !== plan.role || recorded.worktree !== where.worktree || !recorded.thread || !recorded.socket) throw Error('managed role identity or creation outcome unverified');
|
|
218
|
+
if (!applying) {
|
|
219
|
+
plan.thread = recorded.thread; plan.fromSocket = recorded.socket; plan.registryDigest = digest(bytes);
|
|
220
|
+
if (plan.toSocket === plan.fromSocket) throw Error('migration target is already the recorded endpoint');
|
|
221
|
+
}
|
|
222
|
+
unique(where, plan.role, plan.thread, false);
|
|
223
|
+
let journal = applying && fs.existsSync(journalFile) ? JSON.parse(fs.readFileSync(journalFile, 'utf8')) : null;
|
|
224
|
+
if (journal?.state === 'committed') {
|
|
225
|
+
if (recorded.socket !== plan.toSocket || recorded.thread !== plan.thread || !recorded.endpointMigrations?.some(entry => entry.plan === plan.id)) throw Error('committed migration no longer matches registry');
|
|
226
|
+
process.stdout.write(JSON.stringify({state: 'already-migrated', thread: plan.thread, plan: plan.id}) + '\n'); return 0;
|
|
227
|
+
}
|
|
228
|
+
const audit = {plan: plan.id, authority: plan.authority, fromSocket: plan.fromSocket, toSocket: plan.toSocket, nativePolicy: plan.nativePolicy, historyDigest: plan.historyDigest, historyCount: plan.historyCount};
|
|
229
|
+
const nextRegistry = original => ({...original, socket: plan.toSocket, endpointMigrations: [...(original.endpointMigrations || []), audit]});
|
|
230
|
+
const registryAlreadyApplied = Boolean(options.reconcile && journal?.originalRegistry && digest(journal.originalRegistry) === plan.registryDigest && same(recorded, nextRegistry(JSON.parse(journal.originalRegistry))));
|
|
231
|
+
const expectedDigest = registryAlreadyApplied ? digest(bytes) : plan.registryDigest;
|
|
232
|
+
const unchanged = () => {
|
|
233
|
+
binding(where, plan.role);
|
|
234
|
+
if (digest(fs.readFileSync(file)) !== expectedDigest) throw Error('managed role registry changed since inspection; original snapshot not overwritten');
|
|
235
|
+
};
|
|
236
|
+
unchanged();
|
|
237
|
+
if ((!registryAlreadyApplied && recorded.socket !== plan.fromSocket) || recorded.thread !== plan.thread) throw Error('migration source identity mismatch');
|
|
238
|
+
if (journal && !options.reconcile) throw Error('migration outcome unknown; inspect migration-status and explicitly reconcile, no automatic retry');
|
|
239
|
+
if (options.reconcile && !journal) throw Error('no transition exists to reconcile');
|
|
240
|
+
const source = await openHost(plan.fromSocket, context);
|
|
241
|
+
if (!options.reconcile) {
|
|
242
|
+
const snapshot = await inspectSource(source, plan, recorded);
|
|
243
|
+
if (!applying) {
|
|
244
|
+
process.stdout.write(JSON.stringify(savePlan({...plan, ...snapshot})) + '\n'); return 0;
|
|
245
|
+
}
|
|
246
|
+
if (!same(snapshot.nativePolicy, plan.nativePolicy) || snapshot.historyDigest !== plan.historyDigest || snapshot.historyCount !== plan.historyCount) throw Error('native source policy or history changed since inspection');
|
|
247
|
+
unchanged();
|
|
248
|
+
journal = {schema: 'keel-codex-migration/v1', state: 'pending', phase: 'intent', plan, originalRegistry: bytes.toString('utf8')};
|
|
249
|
+
store.writeJsonAtomic(where, journalFile, journal);
|
|
250
|
+
}
|
|
251
|
+
try {
|
|
252
|
+
if (!options.reconcile) {
|
|
253
|
+
// Only release our own source subscription, never cancel a tool/turn or
|
|
254
|
+
// remove another frontend's subscription. Native writer refusal rules.
|
|
255
|
+
const current = (await source.call('thread/read', {threadId: plan.thread, includeTurns: false})).thread;
|
|
256
|
+
verifyThread(current, plan);
|
|
257
|
+
await quiescent(source, plan, current, await history(source, plan.thread));
|
|
258
|
+
journal.phase = 'releasing'; store.writeJsonAtomic(where, journalFile, journal);
|
|
259
|
+
const released = await source.call('thread/unsubscribe', {threadId: plan.thread});
|
|
260
|
+
if (released.status !== 'unsubscribed') throw Error('source subscription release not verified');
|
|
261
|
+
}
|
|
262
|
+
const target = await openHost(plan.toSocket, context);
|
|
263
|
+
const targetThread = (await target.call('thread/read', {threadId: plan.thread, includeTurns: false})).thread;
|
|
264
|
+
verifyThread(targetThread, plan);
|
|
265
|
+
if (options.reconcile) {
|
|
266
|
+
const sourceThread = (await source.call('thread/read', {threadId: plan.thread, includeTurns: false})).thread;
|
|
267
|
+
verifyThread(sourceThread, plan);
|
|
268
|
+
if (sourceThread.status.type !== 'notLoaded') throw Error('source release not verified during reconciliation');
|
|
269
|
+
if (!['idle', 'active'].includes(targetThread.status.type)) throw Error('target is not already loaded; reconciliation will not retry native acquisition');
|
|
270
|
+
}
|
|
271
|
+
const prior = await history(target, plan.thread);
|
|
272
|
+
if (prior.length < plan.historyCount || digest(prior.slice(0, plan.historyCount)) !== plan.historyDigest || (!options.reconcile && prior.length !== plan.historyCount)) throw Error('target original persistent history mismatch');
|
|
273
|
+
journal.phase = options.reconcile ? 'reconciling' : 'acquiring'; store.writeJsonAtomic(where, journalFile, journal);
|
|
274
|
+
const native = await target.call('thread/resume', {threadId: plan.thread});
|
|
275
|
+
verifyThread(native.thread, plan); verifyPolicy(native, plan.nativePolicy);
|
|
276
|
+
if (!['idle', ...(options.reconcile ? ['active'] : [])].includes(native.thread.status.type)) throw Error('target native state changed; registration retained');
|
|
277
|
+
const after = await history(target, plan.thread);
|
|
278
|
+
if (after.length < plan.historyCount || digest(after.slice(0, plan.historyCount)) !== plan.historyDigest || (!options.reconcile && after.length !== plan.historyCount)) throw Error('resumed target original persistent history mismatch');
|
|
279
|
+
journal.phase = 'verified'; store.writeJsonAtomic(where, journalFile, journal);
|
|
280
|
+
unchanged();
|
|
281
|
+
if (!registryAlreadyApplied) store.writeJsonAtomic(where, file, nextRegistry(recorded));
|
|
282
|
+
journal.state = 'committed'; journal.phase = 'committed'; delete journal.error;
|
|
283
|
+
store.writeJsonAtomic(where, journalFile, journal);
|
|
284
|
+
process.stdout.write(JSON.stringify({state: 'migrated', role: plan.role, thread: plan.thread, socket: plan.toSocket, plan: plan.id}) + '\n'); return 0;
|
|
285
|
+
} catch (error) {
|
|
286
|
+
journal.state = 'unknown'; journal.error = error.message;
|
|
287
|
+
try {store.writeJsonAtomic(where, journalFile, journal);} catch { /* Preserve last durable phase if journaling itself fails. */ }
|
|
288
|
+
throw Error(`${error.message}; migration outcome unknown, journal retained; no native rollback claimed`);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
module.exports = {actions, run, policyOf, policyFor, verifyPolicy};
|