@christang/keel 5.230.0 → 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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.230.0",
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
- Existing desktop chats are not adopted. Native write-guard enforcement and compaction
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
 
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.230.0 -->
1
+ <!-- keel:start version=5.231.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the durable authority, and memory or transcripts may only inform.
package/bin/keel.js CHANGED
@@ -108,6 +108,11 @@ Usage:
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
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]
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.230.0",
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.230.0",
9
+ "version": "5.231.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@fission-ai/openspec": "1.14.0"
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@christang/keel",
3
3
  "displayName": "Keel",
4
4
  "description": "Keel OpenSpec execution discipline CLI for Claude Code, Codex, and OpenCode.",
5
- "version": "5.230.0",
5
+ "version": "5.231.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.230.0",
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.230.0",
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",
@@ -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.230.0"
38
+ PACKAGE_VERSION = "5.231.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.230.0"
41
+ PROTOCOL_VERSION = "5.231.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -119,9 +119,12 @@ 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
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]");
@@ -182,8 +185,16 @@ async function run(args) {
182
185
  if (action === "deliver" && (!options.record || !options.text)) throw Error("deliver needs --record and --text");
183
186
  if (action === "handover" && !options.note) throw Error("handover needs --note");
184
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);
185
196
  client = await connect(options.socket, ms);
186
- const host = await client.call("initialize", {clientInfo: {name: "keel", version: "1"}, ...(requestedReviewer || recorded?.approvalsReviewer ? {capabilities: {experimentalApi: true}} : {})});
197
+ const host = await client.call("initialize", {clientInfo: {name: "keel", version: "1"}, ...(requestedReviewer || recorded?.approvalsReviewer || savedPolicy ? {capabilities: {experimentalApi: true}} : {})});
187
198
  if (!host || typeof host.userAgent !== "string" || !host.userAgent) throw Error("Codex host returned no initialization identity");
188
199
  client.notify("initialized");
189
200
  const result = {socket: options.socket, host};
@@ -229,10 +240,11 @@ async function run(args) {
229
240
  } else {
230
241
  // Native writer ownership decides whether the original id can resume.
231
242
  // Restore only the recorded execution cwd; never rewrite role claims.
232
- const resumed = await client.call("thread/resume", {threadId: recorded.thread, cwd: recorded.worktree, runtimeWorkspaceRoots: [recorded.worktree], serviceName: "keel", ...(recorded.approvalsReviewer ? {approvalsReviewer: recorded.approvalsReviewer} : {})}, explicitTimeout ? ms : Math.max(ms, 15000));
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));
233
244
  if (!resumed.thread || resumed.thread.id !== recorded.thread || resumed.thread.cwd !== recorded.worktree) throw Error("recovered managed role identity mismatch; original registry retained");
234
- if (resumed.approvalPolicy !== "on-request") throw Error("recovered thread approval policy mismatch; original registry retained");
235
- if (resumed.sandbox?.type !== "workspaceWrite") throw Error("recovered thread sandbox 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");
236
248
  if (recorded.approvalsReviewer && resumed.approvalsReviewer !== recorded.approvalsReviewer) throw Error("recovered thread reviewer mismatch; original registry retained");
237
249
  if (resumed.thread.status?.type !== "idle") throw Error("recovered thread is not verified idle; original registry retained");
238
250
  Object.assign(result, {state: "recovered", thread: recorded.thread, worktree: recorded.worktree});
@@ -250,15 +262,18 @@ async function run(args) {
250
262
  }
251
263
  Object.assign(result, {state: "already-delivered", turn: claims[key].turn});
252
264
  } else {
253
- if (action === "deliver" && thread.status && (thread.status.type === "notLoaded" || (recorded.approvalsReviewer && thread.status.type === "idle"))) {
265
+ if (action === "deliver" && thread.status && (thread.status.type === "notLoaded" || ((recorded.approvalsReviewer || savedPolicy) && thread.status.type === "idle"))) {
254
266
  // Only this recorded owned identity may be loaded. Keep this same
255
267
  // connection alive through the subsequent turn/start and preserve
256
268
  // saved sandbox/approval settings. An explicitly chosen reviewer
257
269
  // belongs to the managed role and follows its later deliveries.
258
- const resumed = await client.call("thread/resume", {threadId: recorded.thread, serviceName: "keel", ...(recorded.approvalsReviewer ? {approvalsReviewer: recorded.approvalsReviewer} : {})}, explicitTimeout ? ms : Math.max(ms, 15000));
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));
259
271
  thread = resumed.thread;
260
272
  if (!owned(thread)) throw Error("resumed managed role identity mismatch");
261
- if (thread.status?.type === "idle") verifyReviewerPolicy(resumed, recorded.approvalsReviewer);
273
+ if (thread.status?.type === "idle") {
274
+ if (savedPolicy) onboarding.verifyPolicy(resumed, savedPolicy);
275
+ else verifyReviewerPolicy(resumed, recorded.approvalsReviewer);
276
+ }
262
277
  }
263
278
  if (!thread.status || !["idle", "active"].includes(thread.status.type)) {
264
279
  throw Error("managed role state is not verified idle or active; no work started");
@@ -269,7 +284,7 @@ async function run(args) {
269
284
  claims[key] = {record: options.record, state: "pending"};
270
285
  recorded.deliveries = claims;
271
286
  store.writeJsonAtomic(where, file, recorded);
272
- const turn = (await client.call("turn/start", {threadId: recorded.thread, ...(recorded.approvalsReviewer ? {approvalsReviewer: recorded.approvalsReviewer} : {}), 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;
273
288
  if (!turn || !turn.id) throw Error("Codex returned no turn identity; claim retained");
274
289
  claims[key] = {record: options.record, state: "delivered", turn: turn.id};
275
290
  store.writeJsonAtomic(where, file, recorded);
@@ -304,6 +319,7 @@ async function run(args) {
304
319
  } finally {
305
320
  if (client) client.close();
306
321
  if (roleLock) require("node:fs").rmSync(roleLock, {force: true});
322
+ if (registrationLock) require("node:fs").rmSync(registrationLock, {force: true});
307
323
  }
308
324
  }
309
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};