@christang/keel 5.229.3 → 5.230.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.229.3",
3
+ "version": "5.230.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,4 +1,4 @@
1
- <!-- keel:start version=5.229.3 -->
1
+ <!-- keel:start version=5.230.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
@@ -107,7 +107,7 @@ 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
111
  keel tick [--repo <path>] [--json] (one model-free step for a host scheduler; keel tick task prints the job)
112
112
  keel openspec [args...]
113
113
  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.229.3",
3
+ "version": "5.230.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.229.3",
9
+ "version": "5.230.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.229.3",
5
+ "version": "5.230.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.229.3",
3
+ "version": "5.230.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.229.3",
3
+ "version": "5.230.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
+ });
@@ -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.229.3"
38
+ PACKAGE_VERSION = "5.230.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.229.3"
41
+ PROTOCOL_VERSION = "5.230.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -124,14 +124,14 @@ async function run(args) {
124
124
  let roleLock;
125
125
  try {
126
126
  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]");
127
+ 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
128
  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
129
  let explicitSocket = false;
130
130
  let explicitTimeout = false;
131
131
  while (args.length) {
132
132
  const flag = args.shift();
133
133
  if (flag === "--json") options.json = true;
134
- else if (["--socket", "--thread", "--timeout", "--role", "--repo", "--record", "--text", "--note"].includes(flag)) {
134
+ else if (["--socket", "--thread", "--timeout", "--role", "--repo", "--record", "--text", "--note", "--approvals-reviewer"].includes(flag)) {
135
135
  const value = args.shift();
136
136
  if (!value || value.startsWith("--")) throw Error(`${flag} needs a value`);
137
137
  options[flag.slice(2)] = value;
@@ -139,6 +139,9 @@ async function run(args) {
139
139
  if (flag === "--timeout") explicitTimeout = true;
140
140
  } else throw Error(`Unknown argument ${flag}`);
141
141
  }
142
+ const requestedReviewer = options["approvals-reviewer"];
143
+ if (requestedReviewer && !["user", "auto_review"].includes(requestedReviewer)) throw Error("approvals-reviewer must be user or auto_review");
144
+ if (requestedReviewer && action !== "start") throw Error("--approvals-reviewer is only accepted by start");
142
145
  const ms = Number(options.timeout);
143
146
  if (!Number.isInteger(ms) || ms < 50 || ms > 60000) throw Error("timeout must be 50–60000 milliseconds");
144
147
  const fs = require("node:fs");
@@ -167,7 +170,7 @@ async function run(args) {
167
170
  }
168
171
  }
169
172
  if (action === "start" && !options.role) throw Error("start needs --role");
170
- if (["deliver", "handover"].includes(action)) {
173
+ if (["deliver", "handover", "recover"].includes(action)) {
171
174
  if (!recorded) throw Error("operation needs a managed --role");
172
175
  const candidateLock = `${file}.lock`;
173
176
  const fd = fs.openSync(candidateLock, "wx"); fs.closeSync(fd);
@@ -180,34 +183,60 @@ async function run(args) {
180
183
  if (action === "handover" && !options.note) throw Error("handover needs --note");
181
184
  }
182
185
  client = await connect(options.socket, ms);
183
- const host = await client.call("initialize", {clientInfo: {name: "keel", version: "1"}});
186
+ const host = await client.call("initialize", {clientInfo: {name: "keel", version: "1"}, ...(requestedReviewer || recorded?.approvalsReviewer ? {capabilities: {experimentalApi: true}} : {})});
184
187
  if (!host || typeof host.userAgent !== "string" || !host.userAgent) throw Error("Codex host returned no initialization identity");
185
188
  client.notify("initialized");
186
189
  const result = {socket: options.socket, host};
187
- async function initializeThread(thread) {
190
+ function verifyReviewerPolicy(reply, reviewer) {
191
+ if (!reviewer) return;
192
+ if (reply.approvalsReviewer !== reviewer) throw Error("Codex thread reviewer mismatch; original identity retained");
193
+ if (reply.approvalPolicy !== "on-request") throw Error("Codex thread approval policy mismatch; original identity retained");
194
+ if (reply.sandbox?.type !== "workspaceWrite") throw Error("Codex thread sandbox mismatch; original identity retained");
195
+ }
196
+ async function initializeThread(thread, reviewer) {
188
197
  // Native metadata writes materialize fresh persistent threads without a
189
198
  // model turn. Blank thread/start alone has no durable rollout yet.
190
199
  await client.call("thread/name/set", {threadId: thread.id, name: options.role});
200
+ if (reviewer) await client.call("thread/settings/update", {threadId: thread.id, approvalsReviewer: reviewer, approvalPolicy: "on-request"});
191
201
  const verified = (await client.call("thread/read", {threadId: thread.id, includeTurns: false})).thread;
192
202
  if (!verified || verified.id !== thread.id || verified.cwd !== where.worktree) {
193
203
  throw Error("initialized managed role identity mismatch");
194
204
  }
195
205
  }
196
206
  if (action === "start") {
207
+ const reviewerPolicy = requestedReviewer ? {approvalsReviewer: requestedReviewer} : {};
197
208
  fs.mkdirSync(path.dirname(file), {recursive: true});
198
209
  const fd = fs.openSync(file, "wx");
199
- fs.writeFileSync(fd, JSON.stringify({state: "creation-pending", role: options.role, worktree: where.worktree, socket: options.socket}));
210
+ fs.writeFileSync(fd, JSON.stringify({state: "creation-pending", role: options.role, worktree: where.worktree, socket: options.socket, ...reviewerPolicy}));
200
211
  fs.closeSync(fd);
201
212
  reservation = file;
202
- const started = await client.call("thread/start", {cwd: where.worktree, sandbox: "workspace-write", approvalPolicy: "on-request", serviceName: "keel"});
213
+ const started = await client.call("thread/start", {cwd: where.worktree, sandbox: "workspace-write", approvalPolicy: "on-request", serviceName: "keel", ...reviewerPolicy});
203
214
  const thread = started.thread;
204
215
  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
- await initializeThread(thread);
207
- const entry = {state: "managed", role: options.role, thread: thread.id, worktree: where.worktree, socket: options.socket};
216
+ store.writeJsonAtomic(where, file, {state: "creation-pending", role: options.role, thread: thread.id, worktree: where.worktree, socket: options.socket, ...reviewerPolicy});
217
+ verifyReviewerPolicy(started, requestedReviewer);
218
+ await initializeThread(thread, requestedReviewer);
219
+ const entry = {state: "managed", role: options.role, thread: thread.id, worktree: where.worktree, socket: options.socket, ...reviewerPolicy};
208
220
  store.writeJsonAtomic(where, file, entry);
209
221
  store.setRole(where, options.role);
210
222
  Object.assign(result, entry);
223
+ } else if (action === "recover") {
224
+ const original = (await client.call("thread/read", {threadId: recorded.thread, includeTurns: false})).thread;
225
+ if (!original || original.id !== recorded.thread) throw Error("managed role identity mismatch; no recovery attempted");
226
+ if (!original.status || !["idle", "active", "notLoaded"].includes(original.status.type)) throw Error("managed role state is not verified; no recovery attempted");
227
+ if (original.status.type === "active") {
228
+ Object.assign(result, {state: "waiting", thread: recorded.thread});
229
+ } else {
230
+ // Native writer ownership decides whether the original id can resume.
231
+ // 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));
233
+ 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");
236
+ if (recorded.approvalsReviewer && resumed.approvalsReviewer !== recorded.approvalsReviewer) throw Error("recovered thread reviewer mismatch; original registry retained");
237
+ if (resumed.thread.status?.type !== "idle") throw Error("recovered thread is not verified idle; original registry retained");
238
+ Object.assign(result, {state: "recovered", thread: recorded.thread, worktree: recorded.worktree});
239
+ }
211
240
  } else if (["deliver", "handover"].includes(action)) {
212
241
  let thread = (await client.call("thread/read", {threadId: recorded.thread, includeTurns: false})).thread;
213
242
  const owned = value => value && value.id === recorded.thread && value.cwd === recorded.worktree;
@@ -221,12 +250,15 @@ async function run(args) {
221
250
  }
222
251
  Object.assign(result, {state: "already-delivered", turn: claims[key].turn});
223
252
  } else {
224
- if (action === "deliver" && thread.status && thread.status.type === "notLoaded") {
253
+ if (action === "deliver" && thread.status && (thread.status.type === "notLoaded" || (recorded.approvalsReviewer && thread.status.type === "idle"))) {
225
254
  // Only this recorded owned identity may be loaded. Keep this same
226
255
  // connection alive through the subsequent turn/start and preserve
227
- // the thread's saved permissions rather than overriding them.
228
- thread = (await client.call("thread/resume", {threadId: recorded.thread, serviceName: "keel"}, explicitTimeout ? ms : Math.max(ms, 15000))).thread;
256
+ // saved sandbox/approval settings. An explicitly chosen reviewer
257
+ // 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));
259
+ thread = resumed.thread;
229
260
  if (!owned(thread)) throw Error("resumed managed role identity mismatch");
261
+ if (thread.status?.type === "idle") verifyReviewerPolicy(resumed, recorded.approvalsReviewer);
230
262
  }
231
263
  if (!thread.status || !["idle", "active"].includes(thread.status.type)) {
232
264
  throw Error("managed role state is not verified idle or active; no work started");
@@ -237,7 +269,7 @@ async function run(args) {
237
269
  claims[key] = {record: options.record, state: "pending"};
238
270
  recorded.deliveries = claims;
239
271
  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;
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;
241
273
  if (!turn || !turn.id) throw Error("Codex returned no turn identity; claim retained");
242
274
  claims[key] = {record: options.record, state: "delivered", turn: turn.id};
243
275
  store.writeJsonAtomic(where, file, recorded);
@@ -246,11 +278,13 @@ async function run(args) {
246
278
  if (recorded.handover) throw Error("handover outcome unknown; no successor started");
247
279
  recorded.handover = {state: "pending", note: options.note};
248
280
  store.writeJsonAtomic(where, file, recorded);
249
- const next = (await client.call("thread/start", {cwd: recorded.worktree, sandbox: "workspace-write", approvalPolicy: "on-request", serviceName: "keel"})).thread;
281
+ const successor = await client.call("thread/start", {cwd: recorded.worktree, sandbox: "workspace-write", approvalPolicy: "on-request", serviceName: "keel", ...(recorded.approvalsReviewer ? {approvalsReviewer: recorded.approvalsReviewer} : {})});
282
+ const next = successor.thread;
250
283
  if (!next || !next.id || next.cwd !== recorded.worktree) throw Error("successor identity mismatch; handover retained");
251
284
  recorded.handover.thread = next.id;
252
285
  store.writeJsonAtomic(where, file, recorded);
253
- await initializeThread(next);
286
+ verifyReviewerPolicy(successor, recorded.approvalsReviewer);
287
+ await initializeThread(next, recorded.approvalsReviewer);
254
288
  const history = [...(recorded.history || []), {thread: recorded.thread, note: options.note}];
255
289
  delete recorded.handover;
256
290
  Object.assign(recorded, {thread: next.id, history, note: options.note});