@christang/keel 5.229.0 → 5.229.2

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.0",
3
+ "version": "5.229.2",
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.0 -->
1
+ <!-- keel:start version=5.229.2 -->
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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.229.0",
3
+ "version": "5.229.2",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.229.0",
9
+ "version": "5.229.2",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@fission-ai/openspec": "^1.4.1"
@@ -999,9 +999,9 @@
999
999
  }
1000
1000
  },
1001
1001
  "node_modules/zod": {
1002
- "version": "4.4.3",
1003
- "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",
1004
- "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",
1002
+ "version": "4.6.7",
1003
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
1004
+ "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
1005
1005
  "license": "MIT",
1006
1006
  "funding": {
1007
1007
  "url": "https://github.com/sponsors/colinhacks"
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.0",
5
+ "version": "5.229.2",
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.0",
3
+ "version": "5.229.2",
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.0",
3
+ "version": "5.229.2",
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",
@@ -10,8 +10,8 @@ const {spawn}=require('node:child_process');
10
10
  const cli=path.resolve(__dirname,'../bin/keel.js');
11
11
  function run(args,action="status"){return new Promise(resolve=>{const p=spawn(process.execPath,action==='tick'?[cli,'tick',...args]:[cli,'codex',action,...args]);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
12
  test('managed CLI lifecycle, mailbox scheduling and frame boundaries',async()=>{
13
- const dir=fs.mkdtempSync(path.join(os.tmpdir(),'keel-host-'));const sock=path.join(dir,'host.sock');const requests=[];const peers=[];let active=true,serial=0,uncertain=false,invalidHost=false,injectNotice=false;
14
- const server=http.createServer();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 initialized=false;let buf=Buffer.alloc(0);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);const 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.method);if(x.method==='initialized'){initialized=true;continue;}if(!x.id)continue;if(x.method!=='initialize'&&!initialized){s.destroy();return;}const result=x.method==='initialize'?(invalidHost?{}:{userAgent:'test-host'}):x.method==='turn/start'?{turn:uncertain?{}:{id:'turn-fixture'}}:{thread:{id:x.method==='thread/start'?`fixture-thread-${++serial}`:(x.params.threadId||'fixture-thread'),status:{type:active?'active':'idle'},cwd:dir}};const b=Buffer.from(JSON.stringify({id:x.id,result}));const h=b.length<126?Buffer.from([129,b.length]):Buffer.from([129,126,b.length>>8,b.length&255]);const split=Math.floor(b.length/2);const frame=(op,body)=>Buffer.concat([body.length<126?Buffer.from([op,body.length]):Buffer.from([op,126,body.length>>8,body.length&255]),body]);if(injectNotice){const notice=Buffer.from(JSON.stringify({id:x.id,method:'server/notice',params:{}}));s.write(frame(129,notice));}s.write(Buffer.concat([frame(1,b.subarray(0,split)),frame(128,b.subarray(split))]));}});});
13
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'keel-host-'));const sock=path.join(dir,'host.sock');const requests=[];const requestDetails=[];const peers=[];const blank=new Set(),lost=new Set();let active=true,serial=0,uncertain=false,invalidHost=false,injectNotice=false,unloaded=false,resumeActive=false,resumeFails=false,resumeMismatch=false,readMismatch=false,resumeDelay=false,initNameFails=false;
14
+ const server=http.createServer();server.on('upgrade',(req,s)=>{peers.push(s);s.on('end',()=>{for(const id of blank)lost.add(id);});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 initialized=false;let buf=Buffer.alloc(0);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);const 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.method);requestDetails.push(x);if(x.method==='initialized'){initialized=true;continue;}if(!x.id)continue;if(x.method!=='initialize'&&!initialized){s.destroy();return;}if(x.method==='thread/read'&&lost.has(x.params.threadId)){const b=Buffer.from(JSON.stringify({id:x.id,error:{message:'thread not loaded: '+x.params.threadId}}));s.write(Buffer.concat([Buffer.from([129,b.length]),b]));continue;}if(x.method==='thread/name/set'&&!initNameFails)blank.delete(x.params.threadId);if(x.method==='thread/name/set'&&initNameFails){const b=Buffer.from(JSON.stringify({id:x.id,error:{message:'fixture name persistence failure'}}));s.write(Buffer.concat([Buffer.from([129,b.length]),b]));continue;}if(x.method==='thread/resume'){if(resumeFails){const b=Buffer.from(JSON.stringify({id:x.id,error:{message:'fixture resume failure'}}));s.write(Buffer.concat([Buffer.from([129,b.length]),b]));continue;}unloaded=false;if(resumeActive)active=true;}const result=x.method==='initialize'?(invalidHost?{}:{userAgent:'test-host'}):x.method==='turn/start'?{turn:uncertain?{}:{id:'turn-fixture'}}:{thread:{id:x.method==='thread/start'?`fixture-thread-${++serial}`:(x.params.threadId||'fixture-thread'),status:{type:unloaded?'notLoaded':active?'active':'idle'},cwd:(x.method==='thread/read'&&readMismatch)||(x.method==='thread/resume'&&resumeMismatch)?'/wrong-worktree':dir}};if(x.method==='thread/start')blank.add(result.thread.id);const b=Buffer.from(JSON.stringify({id:x.id,result}));const h=b.length<126?Buffer.from([129,b.length]):Buffer.from([129,126,b.length>>8,b.length&255]);const split=Math.floor(b.length/2);const frame=(op,body)=>Buffer.concat([body.length<126?Buffer.from([op,body.length]):Buffer.from([op,126,body.length>>8,body.length&255]),body]);if(injectNotice){const notice=Buffer.from(JSON.stringify({id:x.id,method:'server/notice',params:{}}));s.write(frame(129,notice));}const reply=()=>{if(!s.destroyed)s.write(Buffer.concat([frame(1,b.subarray(0,split)),frame(128,b.subarray(split))]));};if(resumeDelay&&x.method==='thread/resume')setTimeout(reply,5500).unref();else reply();}});});
15
15
  await new Promise(r=>server.listen(sock,r));
16
16
  try{const x=await run(['--socket',sock,'--thread','fixture-thread','--json']);assert.equal(x.code,0,x.err);assert.equal(JSON.parse(x.out).thread.status.type,'active');assert.deepEqual(requests.filter(x=>x!=='initialized'),['initialize','thread/read']);
17
17
  active=false;const {spawnSync}=require('node:child_process');spawnSync('git',['init','-q',dir]);
@@ -21,12 +21,13 @@ test('managed CLI lifecycle, mailbox scheduling and frame boundaries',async()=>{
21
21
  assert.equal(JSON.parse(started.out).role,'test-role');
22
22
  const again=await run(['--socket',sock,'--repo',dir,'--role','test-role'],'start');assert.notEqual(again.code,0);assert.match(again.err,/already|exists/);
23
23
  const own=await run(['--repo',dir,'--role','test-role','--json']);assert.equal(own.code,0,own.err);
24
+ assert.deepEqual(requestDetails.find(x=>x.method==='thread/name/set')?.params,{threadId:'fixture-thread-1',name:'test-role'},'successful start must persist its original identity through native naming');
24
25
  assert.equal(requests.filter(x=>x==='thread/start').length,1);
25
26
  const message=['--repo',dir,'--role','test-role','--record','fixture-record','--text','Run keel chat unread','--json'];
26
27
  const sent=await run(message,'deliver');assert.equal(sent.code,0,sent.err);
27
28
  const duplicate=await run(message,'deliver');assert.equal(duplicate.code,0,duplicate.err);assert.equal(requests.filter(x=>x==='turn/start').length,1);
28
29
  active=true;const waiting=await run(['--repo',dir,'--role','test-role','--note','finish fixture','--json'],'handover');assert.equal(waiting.code,0,waiting.err);assert.equal(JSON.parse(waiting.out).state,'waiting');assert.equal(serial,1);
29
- active=false;const handed=await run(['--repo',dir,'--role','test-role','--note','finish fixture','--json'],'handover');assert.equal(handed.code,0,handed.err);assert.equal(serial,2);
30
+ active=false;const handed=await run(['--repo',dir,'--role','test-role','--note','finish fixture','--json'],'handover');assert.equal(handed.code,0,handed.err);assert.equal(serial,2);assert.ok(requestDetails.some(x=>x.method==='thread/name/set'&&x.params.threadId==='fixture-thread-2'&&x.params.name==='test-role'),'successor must be persisted before handover succeeds');
30
31
  const store=require('../src/core/chat/store');const where=store.requireLocation(dir);
31
32
  store.createGroup(where,'owner','team',['test-role']);
32
33
  store.writeRecord(where,{group:'team',kind:'message',from:'owner',mentions:['test-role'],text:'addressed fixture'});
@@ -43,9 +44,31 @@ test('managed CLI lifecycle, mailbox scheduling and frame boundaries',async()=>{
43
44
 
44
45
  uncertain=false;const large=await run(['--repo',dir,'--role','test-role','--record','large-record','--text','x'.repeat(70000),'--json'],'deliver');assert.equal(large.code,0,large.err);
45
46
  const raceBefore=requests.filter(x=>x==='turn/start').length;const raceArgs=['--repo',dir,'--role','test-role','--record','concurrent-record','--text','concurrent fixture','--json'];const raced=await Promise.all([run(raceArgs,'deliver'),run(raceArgs,'deliver')]);assert.ok(raced.some(x=>x.code===0));assert.equal(requests.filter(x=>x==='turn/start').length,raceBefore+1);
47
+ // An unloaded owned thread is not an unrelated desktop session.
48
+ const recoveryArgs=record=>['--repo',dir,'--role','test-role','--record',record,'--text','recovery round','--json'];
49
+ const resumes=()=>requests.filter(x=>x==='thread/resume').length;
50
+ const turns=()=>requests.filter(x=>x==='turn/start').length;
51
+ unloaded=true;let rb=resumes(),tb=turns();
52
+ const unloadedDuplicate=await run(recoveryArgs('large-record'),'deliver');assert.equal(unloadedDuplicate.code,0,unloadedDuplicate.err);assert.equal(JSON.parse(unloadedDuplicate.out).state,'already-delivered');assert.equal(resumes(),rb);assert.equal(turns(),tb);
53
+ const recovered=await run(recoveryArgs('recovery-record'),'deliver');assert.equal(recovered.code,0,recovered.err);assert.equal(JSON.parse(recovered.out).state,'delivered');assert.equal(resumes(),rb+1);assert.equal(turns(),tb+1);assert.equal(serial,2);
54
+ const resumeRequest=requestDetails.find(x=>x.method==='thread/resume');assert.deepEqual(resumeRequest.params,{threadId:'fixture-thread-2',serviceName:'keel'});
55
+ unloaded=true;rb=resumes();tb=turns();const recoveredDuplicate=await run(recoveryArgs('recovery-record'),'deliver');assert.equal(recoveredDuplicate.code,0,recoveredDuplicate.err);assert.equal(resumes(),rb);assert.equal(turns(),tb);
56
+ const unknown=await run(recoveryArgs('uncertain-record'),'deliver');assert.notEqual(unknown.code,0);assert.match(unknown.err,/unknown/);assert.equal(resumes(),rb);
57
+ resumeActive=true;const busyRecovery=await run(recoveryArgs('busy-recovery'),'deliver');assert.equal(busyRecovery.code,0,busyRecovery.err);assert.equal(JSON.parse(busyRecovery.out).state,'waiting');assert.equal(turns(),tb);resumeActive=false;active=false;
58
+ unloaded=true;resumeFails=true;const failedRecovery=await run(recoveryArgs('failed-recovery'),'deliver');assert.notEqual(failedRecovery.code,0);assert.match(failedRecovery.err,/fixture resume failure/);assert.equal(turns(),tb);resumeFails=false;
59
+ unloaded=true;resumeMismatch=true;const mismatchRecovery=await run(recoveryArgs('mismatch-recovery'),'deliver');assert.notEqual(mismatchRecovery.code,0);assert.match(mismatchRecovery.err,/identity/);assert.equal(turns(),tb);resumeMismatch=false;
60
+ unloaded=true;readMismatch=true;rb=resumes();const wrongRead=await run(recoveryArgs('wrong-read'),'deliver');assert.notEqual(wrongRead.code,0);assert.equal(resumes(),rb);readMismatch=false;
61
+ unloaded=true;resumeDelay=true;const slowResume=await run(recoveryArgs('cold-recovery'),'deliver');assert.equal(slowResume.code,0,slowResume.err);unloaded=true;const explicitDeadline=await run([...recoveryArgs('short-deadline'),'--timeout','100'],'deliver');assert.notEqual(explicitDeadline.code,0);assert.match(explicitDeadline.err,/thread\/resume timeout/);resumeDelay=false;unloaded=true;rb=resumes();tb=turns();
62
+ const wrongEndpoint=await run([...recoveryArgs('wrong-endpoint'),'--socket',path.join(dir,'other.sock')],'deliver');assert.notEqual(wrongEndpoint.code,0);assert.match(wrongEndpoint.err,/endpoint mismatch/);assert.equal(resumes(),rb);
63
+ const roleFile=path.join(dir,'.git/keel-chat/codex-roles/test-role.json'),savedRole=fs.readFileSync(roleFile);fs.unlinkSync(roleFile);const notOwned=await run(recoveryArgs('not-owned'),'deliver');assert.notEqual(notOwned.code,0);assert.equal(resumes(),rb);fs.writeFileSync(roleFile,savedRole);
64
+ const unloadedHandover=await run(['--repo',dir,'--role','test-role','--note','not an implicit resume'],'handover');assert.notEqual(unloadedHandover.code,0);assert.equal(resumes(),rb);assert.equal(serial,2);unloaded=false;
46
65
  injectNotice=true;const notified=await run(['--socket',sock,'--json']);assert.equal(notified.code,0,notified.err);assert.equal(JSON.parse(notified.out).host.userAgent,'test-host');injectNotice=false;
47
66
  invalidHost=true;const malformed=await run(['--socket',sock,'--json']);assert.notEqual(malformed.code,0);assert.match(malformed.err,/identity/i);invalidHost=false;
48
- const bad=await run(['--socket',path.join(dir,'missing'),'--timeout','100']);assert.notEqual(bad.code,0);assert.match(bad.err,/connect|ENOENT/i);}finally{peers.forEach(s=>s.destroy());await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});}
67
+ const bad=await run(['--socket',path.join(dir,'missing'),'--timeout','100']);assert.notEqual(bad.code,0);assert.match(bad.err,/connect|ENOENT/i);
68
+ initNameFails=true;active=false;const beforeFailedHandover=serial;const failedInitHandover=await run(['--repo',dir,'--role','test-role','--note','retain failed successor','--json'],'handover');assert.notEqual(failedInitHandover.code,0);assert.match(failedInitHandover.err,/fixture name persistence failure/);const pendingHandover=JSON.parse(fs.readFileSync(roleFile));assert.equal(pendingHandover.thread,'fixture-thread-2');assert.equal(pendingHandover.handover.thread,`fixture-thread-${beforeFailedHandover+1}`);const retryHandover=await run(['--repo',dir,'--role','test-role','--note','retry must not replace'],'handover');assert.notEqual(retryHandover.code,0);assert.equal(serial,beforeFailedHandover+1);
69
+ fs.unlinkSync(roleFile);const beforeFailedStart=serial;const failedInitStart=await run(['--socket',sock,'--repo',dir,'--role','test-role','--json'],'start');assert.notEqual(failedInitStart.code,0);assert.match(failedInitStart.err,/fixture name persistence failure/);const pendingStart=JSON.parse(fs.readFileSync(roleFile));assert.equal(pendingStart.state,'creation-pending');assert.equal(pendingStart.thread,`fixture-thread-${beforeFailedStart+1}`);const retryStart=await run(['--socket',sock,'--repo',dir,'--role','test-role'],'start');assert.notEqual(retryStart.code,0);assert.equal(serial,beforeFailedStart+1);
70
+ initNameFails=false;fs.unlinkSync(roleFile);readMismatch=true;const badIdentityStart=await run(['--socket',sock,'--repo',dir,'--role','test-role'],'start');assert.notEqual(badIdentityStart.code,0);assert.match(badIdentityStart.err,/identity/);
71
+ }finally{peers.forEach(s=>s.destroy());await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});}
49
72
  });
50
73
  test('silent endpoint fails before the deadline',async()=>{
51
74
  const dir=fs.mkdtempSync(path.join(os.tmpdir(),'keel-silent-')),sock=path.join(dir,'host.sock');const server=http.createServer();const peers=[];server.on('connection',s=>peers.push(s));await new Promise(r=>server.listen(sock,r));
@@ -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.0"
38
+ PACKAGE_VERSION = "5.229.2"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.229.0"
41
+ PROTOCOL_VERSION = "5.229.2"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -99,11 +99,11 @@ function connect(socketPath, timeout = 5000) {
99
99
  socket.on('close', () => fail(Error('Codex host disconnected')));
100
100
  opened = true;
101
101
  resolve({
102
- call(method, params) {
102
+ call(method, params, callTimeout = timeout) {
103
103
  return new Promise((resolveCall, rejectCall) => {
104
104
  if (closed) return rejectCall(Error('Codex host disconnected'));
105
105
  const id = ++sequence;
106
- const timer = setTimeout(() => fail(Error(`Codex ${method} timeout`)), timeout);
106
+ const timer = setTimeout(() => fail(Error(`Codex ${method} timeout`)), callTimeout);
107
107
  pending.set(id, {resolve: resolveCall, reject: rejectCall, timer});
108
108
  try {send(1, Buffer.from(JSON.stringify({id, method, params})));}
109
109
  catch (error) {fail(error);}
@@ -127,6 +127,7 @@ async function run(args) {
127
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]");
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
+ let explicitTimeout = false;
130
131
  while (args.length) {
131
132
  const flag = args.shift();
132
133
  if (flag === "--json") options.json = true;
@@ -135,6 +136,7 @@ async function run(args) {
135
136
  if (!value || value.startsWith("--")) throw Error(`${flag} needs a value`);
136
137
  options[flag.slice(2)] = value;
137
138
  if (flag === "--socket") explicitSocket = true;
139
+ if (flag === "--timeout") explicitTimeout = true;
138
140
  } else throw Error(`Unknown argument ${flag}`);
139
141
  }
140
142
  const ms = Number(options.timeout);
@@ -182,6 +184,15 @@ async function run(args) {
182
184
  if (!host || typeof host.userAgent !== "string" || !host.userAgent) throw Error("Codex host returned no initialization identity");
183
185
  client.notify("initialized");
184
186
  const result = {socket: options.socket, host};
187
+ async function initializeThread(thread) {
188
+ // Native metadata writes materialize fresh persistent threads without a
189
+ // model turn. Blank thread/start alone has no durable rollout yet.
190
+ await client.call("thread/name/set", {threadId: thread.id, name: options.role});
191
+ const verified = (await client.call("thread/read", {threadId: thread.id, includeTurns: false})).thread;
192
+ if (!verified || verified.id !== thread.id || verified.cwd !== where.worktree) {
193
+ throw Error("initialized managed role identity mismatch");
194
+ }
195
+ }
185
196
  if (action === "start") {
186
197
  fs.mkdirSync(path.dirname(file), {recursive: true});
187
198
  const fd = fs.openSync(file, "wx");
@@ -191,36 +202,61 @@ async function run(args) {
191
202
  const started = await client.call("thread/start", {cwd: where.worktree, sandbox: "workspace-write", approvalPolicy: "on-request", serviceName: "keel"});
192
203
  const thread = started.thread;
193
204
  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);
194
207
  const entry = {state: "managed", role: options.role, thread: thread.id, worktree: where.worktree, socket: options.socket};
195
208
  store.writeJsonAtomic(where, file, entry);
196
209
  store.setRole(where, options.role);
197
210
  Object.assign(result, entry);
198
211
  } else if (["deliver", "handover"].includes(action)) {
199
- const thread = (await client.call("thread/read", {threadId: recorded.thread, includeTurns: false})).thread;
200
- if (!thread || thread.id !== recorded.thread || thread.cwd !== recorded.worktree) throw Error("managed role identity mismatch");
201
- if (!thread.status || !["idle", "active"].includes(thread.status.type)) throw Error("managed role state is not verified idle or active; no work started");
212
+ let thread = (await client.call("thread/read", {threadId: recorded.thread, includeTurns: false})).thread;
213
+ const owned = value => value && value.id === recorded.thread && value.cwd === recorded.worktree;
214
+ if (!owned(thread)) throw Error("managed role identity mismatch");
202
215
  const claims = recorded.deliveries || {};
203
216
  const key = options.record ? crypto.createHash("sha256").update(options.record).digest("hex") : null;
204
217
  if (action === "deliver" && claims[key]) {
205
- if (claims[key].state !== "delivered") throw Error("delivery outcome unknown; claim retained, no retry started");
218
+ // Deduplication is a recorded outcome, not a reason to load a thread.
219
+ if (claims[key].state !== "delivered" || typeof claims[key].turn !== "string" || !claims[key].turn) {
220
+ throw Error("delivery outcome unknown; claim retained, no retry started");
221
+ }
206
222
  Object.assign(result, {state: "already-delivered", turn: claims[key].turn});
207
- } else if (thread.status.type === "active") {
208
- Object.assign(result, {state: "waiting", thread: recorded.thread});
209
- } else if (action === "deliver") {
210
- claims[key] = {record: options.record, state: "pending"};
211
- recorded.deliveries = claims; store.writeJsonAtomic(where, file, recorded);
212
- 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;
213
- if (!turn || !turn.id) throw Error("Codex returned no turn identity; claim retained");
214
- claims[key] = {record: options.record, state: "delivered", turn: turn.id};
215
- store.writeJsonAtomic(where, file, recorded); Object.assign(result, {state: "delivered", turn: turn.id});
216
223
  } else {
217
- if (recorded.handover) throw Error("handover outcome unknown; no successor started");
218
- recorded.handover = {state: "pending", note: options.note}; store.writeJsonAtomic(where, file, recorded);
219
- const next = (await client.call("thread/start", {cwd: recorded.worktree, sandbox: "workspace-write", approvalPolicy: "on-request", serviceName: "keel"})).thread;
220
- if (!next || !next.id || next.cwd !== recorded.worktree) throw Error("successor identity mismatch; handover retained");
221
- const history = [...(recorded.history || []), {thread: recorded.thread, note: options.note}];
222
- delete recorded.handover; Object.assign(recorded, {thread: next.id, history, note: options.note});
223
- store.writeJsonAtomic(where, file, recorded); Object.assign(result, {state: "handed-over", thread: next.id, note: options.note});
224
+ if (action === "deliver" && thread.status && thread.status.type === "notLoaded") {
225
+ // Only this recorded owned identity may be loaded. Keep this same
226
+ // 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;
229
+ if (!owned(thread)) throw Error("resumed managed role identity mismatch");
230
+ }
231
+ if (!thread.status || !["idle", "active"].includes(thread.status.type)) {
232
+ throw Error("managed role state is not verified idle or active; no work started");
233
+ }
234
+ if (thread.status.type === "active") {
235
+ Object.assign(result, {state: "waiting", thread: recorded.thread});
236
+ } else if (action === "deliver") {
237
+ claims[key] = {record: options.record, state: "pending"};
238
+ recorded.deliveries = claims;
239
+ 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;
241
+ if (!turn || !turn.id) throw Error("Codex returned no turn identity; claim retained");
242
+ claims[key] = {record: options.record, state: "delivered", turn: turn.id};
243
+ store.writeJsonAtomic(where, file, recorded);
244
+ Object.assign(result, {state: "delivered", turn: turn.id});
245
+ } else {
246
+ if (recorded.handover) throw Error("handover outcome unknown; no successor started");
247
+ recorded.handover = {state: "pending", note: options.note};
248
+ 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;
250
+ if (!next || !next.id || next.cwd !== recorded.worktree) throw Error("successor identity mismatch; handover retained");
251
+ recorded.handover.thread = next.id;
252
+ store.writeJsonAtomic(where, file, recorded);
253
+ await initializeThread(next);
254
+ const history = [...(recorded.history || []), {thread: recorded.thread, note: options.note}];
255
+ delete recorded.handover;
256
+ Object.assign(recorded, {thread: next.id, history, note: options.note});
257
+ store.writeJsonAtomic(where, file, recorded);
258
+ Object.assign(result, {state: "handed-over", thread: next.id, note: options.note});
259
+ }
224
260
  }
225
261
  } else if (options.thread) {
226
262
  result.thread = (await client.call("thread/read", {threadId: options.thread, includeTurns: false})).thread;
@@ -263,7 +299,7 @@ function wakeManaged(where, onlyRole = null) {
263
299
  const child = require('node:child_process').spawnSync(process.execPath, [
264
300
  path.resolve(__dirname, '../../bin/keel.js'), 'codex', 'deliver',
265
301
  '--repo', entry.worktree, '--role', role, '--record', record.id, '--text', prompt, '--json',
266
- ], {encoding: 'utf8', timeout: 20000});
302
+ ], {encoding: 'utf8', timeout: 40000});
267
303
  let result;
268
304
  try {result = JSON.parse(child.stdout);} catch {result = {};}
269
305
  if (child.error || child.status !== 0) result.error = child.error ? child.error.message : child.stderr.trim();