@christang/keel 5.231.6 → 5.231.7

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.231.6",
3
+ "version": "5.231.7",
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.231.6 -->
1
+ <!-- keel:start version=5.231.7 -->
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
@@ -109,6 +109,7 @@ Usage:
109
109
  keel sync status [--repo <path>] [--verify] [--remote <name>] [--json] (what exists only on this machine; fetches nothing, --verify asks the remote its sha)
110
110
  keel patrol [--issues <file>] [--idle <dur>] [--since-last [--notify]] [--nudge] [--json] [--repo <path>] (the coordinator's patrol; keel patrol task prints its schedule)
111
111
  keel codex status|start|deliver|handover|drain|recover [--repo <path>] [--role <role>] [--socket <path>] [--json] (managed Codex roles; explicit host identity)
112
+ keel codex status [--repo <path>] --role <role> --record <id> [--json] (read the durable delivery receipt locally)
112
113
  keel codex inspect-registration --repo <path> --role <role> --thread <id> --socket <path> --authority <reference>
113
114
  keel codex register --plan <json-file> [--json]
114
115
  keel codex inspect-migration --repo <path> --role <role> --to-socket <path> --authority <reference>
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.231.6",
3
+ "version": "5.231.7",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.231.6",
9
+ "version": "5.231.7",
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.231.6",
5
+ "version": "5.231.7",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.231.6",
3
+ "version": "5.231.7",
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.231.6",
3
+ "version": "5.231.7",
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",
@@ -8,7 +8,7 @@ const path=require('node:path');
8
8
  const fs=require('node:fs');
9
9
  const {spawn}=require('node:child_process');
10
10
  const cli=path.resolve(__dirname,'../bin/keel.js');
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}));});}
11
+ function run(args,action="status"){return new Promise(resolve=>{const p=spawn(process.execPath,['chat','tick'].includes(action)?[cli,action,...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
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
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();}});});
@@ -28,6 +28,22 @@ test('managed CLI lifecycle, mailbox scheduling and frame boundaries',async()=>{
28
28
  const duplicate=await run(message,'deliver');assert.equal(duplicate.code,0,duplicate.err);assert.equal(requests.filter(x=>x==='turn/start').length,1);
29
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);
30
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');
31
+ const receiptFile=path.join(dir,'.git/keel-chat/codex-roles/test-role.json');
32
+ const receiptArgs=['--repo',dir,'--role','test-role','--json'];
33
+ const inspectReceipt=async record=>{
34
+ const before=fs.readFileSync(receiptFile);
35
+ const nativeRequests=requests.length;
36
+ const query=await run([...receiptArgs,'--record',record]);
37
+ assert.equal(query.code,0,query.err);
38
+ const parsed=JSON.parse(query.out);
39
+ return {parsed,before,nativeRequests};
40
+ };
41
+ const original=await inspectReceipt('fixture-record');
42
+ assert.deepEqual(original.parsed,{
43
+ role:'test-role',record:'fixture-record',state:'delivered',thread:'fixture-thread-1',turn:JSON.parse(sent.out).turn,
44
+ },'delivery receipt must preserve its original thread');
45
+ assert.equal(requests.length,original.nativeRequests);
46
+ assert.deepEqual(fs.readFileSync(receiptFile),original.before);
31
47
  const store=require('../src/core/chat/store');const where=store.requireLocation(dir);
32
48
  store.createGroup(where,'owner','team',['test-role']);
33
49
  store.writeRecord(where,{group:'team',kind:'message',from:'owner',mentions:['test-role'],text:'addressed fixture'});
@@ -36,11 +52,50 @@ test('managed CLI lifecycle, mailbox scheduling and frame boundaries',async()=>{
36
52
  const drained=await run(['--repo',dir,'--json'],'drain');assert.equal(drained.code,0,drained.err);assert.equal(requests.filter(x=>x==='turn/start').length,beforeDrain+1);
37
53
  const drainedAgain=await run(['--repo',dir,'--json'],'drain');assert.equal(drainedAgain.code,0,drainedAgain.err);assert.equal(requests.filter(x=>x==='turn/start').length,beforeDrain+1);
38
54
  const beforeTick=requests.filter(x=>x==='turn/start').length;
39
- store.writeRecord(where,{group:'team',kind:'message',from:'owner',mentions:['test-role'],text:'tick addressed fixture'});
55
+ const portableTodo=store.writeRecord(where,{group:'team',kind:'todo',from:'owner',assignee:'test-role',text:'tick addressed fixture'});
56
+ const readPortable=async ({id})=>{
57
+ const registryBefore=fs.readFileSync(receiptFile);
58
+ const nativeRequests=requests.length;
59
+ const read=await run(['--repo',dir,'show',id,'--json'],'chat');
60
+ assert.equal(read.code,0,read.err);
61
+ assert.equal(requests.length,nativeRequests,'query must not contact app-server');
62
+ assert.deepEqual(fs.readFileSync(receiptFile),registryBefore,'query must preserve the registry');
63
+ const view=JSON.parse(read.out);
64
+ assert.deepEqual(view.task,{id,state:'open',closureRecordId:null});
65
+ return view.delivery;
66
+ };
67
+ assert.deepEqual(await readPortable(portableTodo),{state:'unobserved'},'portable query needs an unobserved delivery state');
40
68
  const ticked=await run(['--repo',dir,'--json'],'tick');assert.equal(ticked.code,0,ticked.err);assert.ok(JSON.parse(ticked.out).codex.some(x=>x.state==='delivered'));assert.equal(requests.filter(x=>x==='turn/start').length,beforeTick+1);
41
- uncertain=true;const failedMessage=['--repo',dir,'--role','test-role','--record','uncertain-record','--text','read pending','--json'];const failed=await run(failedMessage,'deliver');assert.notEqual(failed.code,0);const retried=await run(failedMessage,'deliver');assert.notEqual(retried.code,0);assert.match(retried.err,/unknown/);assert.equal(requests.filter(x=>x==='turn/start').length,4);
69
+ assert.deepEqual(await readPortable(portableTodo),{state:'acknowledged'});
70
+ const noReceipt=store.writeRecord(where,{group:'team',kind:'todo',from:'test-role',assignee:'owner',text:'no native receipt'});
71
+ assert.deepEqual(await readPortable(noReceipt),{state:'unobserved'});
72
+ const uncertainTodo=store.writeRecord(where,{group:'team',kind:'todo',from:'owner',assignee:'test-role',text:'ambiguous native receipt'});
73
+ uncertain=true;const failedMessage=['--repo',dir,'--role','test-role','--record',uncertainTodo.id,'--text','read pending','--json'];const failed=await run(failedMessage,'deliver');assert.notEqual(failed.code,0);const retried=await run(failedMessage,'deliver');assert.notEqual(retried.code,0);assert.match(retried.err,/unknown/);assert.equal(requests.filter(x=>x==='turn/start').length,4);
42
74
  const lock=path.join(dir,'.git/keel-chat/codex-roles/test-role.json.lock');fs.writeFileSync(lock,'owned by another process');const locked=await run(message,'deliver');assert.notEqual(locked.code,0);assert.equal(fs.readFileSync(lock,'utf8'),'owned by another process');fs.unlinkSync(lock);
43
75
  const registry=JSON.parse(fs.readFileSync(path.join(dir,'.git/keel-chat/codex-roles/test-role.json')));assert.equal(registry.history.length,1);assert.equal(registry.history[0].note,'finish fixture');
76
+ const pending=await inspectReceipt(uncertainTodo.id);
77
+ assert.deepEqual(pending.parsed,{role:'test-role',record:uncertainTodo.id,state:'unknown',thread:'fixture-thread-2',turn:null});
78
+ assert.equal(requests.length,pending.nativeRequests);
79
+ assert.deepEqual(fs.readFileSync(receiptFile),pending.before);
80
+ assert.deepEqual(await readPortable(uncertainTodo),{state:'unknown'});
81
+ fs.writeFileSync(receiptFile,'{');
82
+ try {
83
+ assert.deepEqual(await readPortable(portableTodo),{state:'unknown'});
84
+ } finally {
85
+ fs.writeFileSync(receiptFile,pending.before);
86
+ }
87
+ const absent=await inspectReceipt('unrecorded-fixture');
88
+ assert.deepEqual(absent.parsed,{role:'test-role',record:'unrecorded-fixture',state:'unrecorded',thread:null,turn:null});
89
+ assert.equal(requests.length,absent.nativeRequests);
90
+ const legacyRecord='legacy-receipt';
91
+ const legacyKey=require('node:crypto').createHash('sha256').update(legacyRecord).digest('hex');
92
+ registry.deliveries[legacyKey]={record:legacyRecord,state:'delivered',turn:'old-native-turn'};
93
+ fs.writeFileSync(receiptFile,JSON.stringify(registry));
94
+ const legacy=await inspectReceipt(legacyRecord);
95
+ assert.deepEqual(legacy.parsed,{role:'test-role',record:legacyRecord,state:'delivered',thread:null,turn:'old-native-turn'});
96
+ assert.equal(requests.length,legacy.nativeRequests);
97
+ assert.deepEqual(fs.readFileSync(receiptFile),legacy.before);
98
+
44
99
 
45
100
  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);
46
101
  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);
@@ -53,7 +108,7 @@ test('managed CLI lifecycle, mailbox scheduling and frame boundaries',async()=>{
53
108
  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
109
  const resumeRequest=requestDetails.find(x=>x.method==='thread/resume');assert.deepEqual(resumeRequest.params,{threadId:'fixture-thread-2',serviceName:'keel'});
55
110
  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);
111
+ const unknown=await run(recoveryArgs(uncertainTodo.id),'deliver');assert.notEqual(unknown.code,0);assert.match(unknown.err,/unknown/);assert.equal(resumes(),rb);
57
112
  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
113
  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
114
  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;
@@ -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.231.6"
38
+ PACKAGE_VERSION = "5.231.7"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.231.6"
41
+ PROTOCOL_VERSION = "5.231.7"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -8,6 +8,7 @@
8
8
  const fs = require("fs");
9
9
  const path = require("path");
10
10
  const { spawnSync } = require("child_process");
11
+ const { listWorktrees } = require("./worktrees");
11
12
 
12
13
  const REMOTE = "origin";
13
14
 
@@ -80,9 +81,8 @@ function refs(cwd, prefix) {
80
81
  }
81
82
 
82
83
  function checkedOut(cwd) {
83
- const listed = git(cwd, ["worktree", "list", "--porcelain"]);
84
- return new Set(listed.out.split("\n").filter((line) => line.startsWith("branch refs/heads/"))
85
- .map((line) => line.slice("branch refs/heads/".length)));
84
+ const checkedOutBranches = listWorktrees(cwd, { optional: true }).map((row) => row.branch).filter(Boolean);
85
+ return new Set(checkedOutBranches);
86
86
  }
87
87
 
88
88
  // Branches a worktree bound to the role has checked out, from its own HEAD
@@ -498,6 +498,8 @@ function dispatch(where, options) {
498
498
  if (record.kind === "todo") {
499
499
  const closure = store.todoClosure(where, record);
500
500
  result.task = { id: record.id, state: closure ? "closed" : "open", closureRecordId: closure ? closure.id : null };
501
+ const { recordedDeliveryState } = require("../codex-host");
502
+ result.delivery = { state: recordedDeliveryState(where, record.assignee, record.id) };
501
503
  }
502
504
  out(JSON.stringify(result));
503
505
  } else out([`${record.group} ${formatLine(record)}`, `read by: ${readers.join(", ") || "nobody yet"}`, ...(acks ? ackLines(acks) : [])].join("\n"));
@@ -118,6 +118,35 @@ function connect(socketPath, timeout = 5000) {
118
118
  });
119
119
  }
120
120
 
121
+ function deliveryKey(record) {
122
+ return crypto.createHash("sha256").update(record).digest("hex");
123
+ }
124
+
125
+ function deliveryReceipt(role, record) {
126
+ const claim = role.deliveries?.[deliveryKey(record)];
127
+ if (claim && claim.record !== record) throw Error("managed delivery claim identity mismatch");
128
+ const turn = claim?.state === "delivered" && typeof claim.turn === "string" && claim.turn ? claim.turn : null;
129
+ const thread = typeof claim?.thread === "string" && claim.thread ? claim.thread : null;
130
+ const state = !claim ? "unrecorded" : turn ? "delivered" : "unknown";
131
+ return { role: role.role, record, state, thread, turn };
132
+ }
133
+
134
+ function recordedDeliveryState(where, assignee, record) {
135
+ const fs = require("node:fs");
136
+ const store = require("./chat/store");
137
+ try {
138
+ store.checkName(assignee, "Assignee");
139
+ const file = path.join(where.root, "codex-roles", `${assignee}.json`);
140
+ const role = JSON.parse(fs.readFileSync(file, "utf8"));
141
+ if (role?.role !== assignee || role.state !== "managed") return "unknown";
142
+ const receipt = deliveryReceipt(role, record);
143
+ if (receipt.state === "delivered") return "acknowledged";
144
+ return receipt.state === "unrecorded" ? "unobserved" : "unknown";
145
+ } catch (error) {
146
+ return error.code === "ENOENT" ? "unobserved" : "unknown";
147
+ }
148
+ }
149
+
121
150
  async function run(args) {
122
151
  const onboarding = require("./codex-onboarding");
123
152
  if (onboarding.actions.includes(args[0])) return onboarding.run(args, {connect});
@@ -172,6 +201,13 @@ async function run(args) {
172
201
  options.thread = recorded.thread;
173
202
  }
174
203
  }
204
+ if (action === "status" && options.record) {
205
+ if (!recorded || recorded.role !== options.role) throw Error("delivery receipt needs an owned --role");
206
+ const receipt = deliveryReceipt(recorded, options.record);
207
+ process.stdout.write((options.json ? JSON.stringify(receipt)
208
+ : `Codex delivery ${receipt.record}: ${receipt.state}${receipt.thread ? ` (thread ${receipt.thread})` : ""}`) + "\n");
209
+ return 0;
210
+ }
175
211
  if (action === "start" && !options.role) throw Error("start needs --role");
176
212
  if (["deliver", "handover", "recover"].includes(action)) {
177
213
  if (!recorded) throw Error("operation needs a managed --role");
@@ -256,7 +292,7 @@ async function run(args) {
256
292
  const owned = value => value && value.id === recorded.thread && value.cwd === recorded.worktree;
257
293
  if (!owned(thread)) throw Error("managed role identity mismatch");
258
294
  const claims = recorded.deliveries || {};
259
- const key = options.record ? crypto.createHash("sha256").update(options.record).digest("hex") : null;
295
+ const key = options.record ? deliveryKey(options.record) : null;
260
296
  if (action === "deliver" && claims[key]) {
261
297
  // Deduplication is a recorded outcome, not a reason to load a thread.
262
298
  if (claims[key].state !== "delivered" || typeof claims[key].turn !== "string" || !claims[key].turn) {
@@ -283,12 +319,12 @@ async function run(args) {
283
319
  if (thread.status.type === "active") {
284
320
  Object.assign(result, {state: "waiting", thread: recorded.thread});
285
321
  } else if (action === "deliver") {
286
- claims[key] = {record: options.record, state: "pending"};
322
+ claims[key] = {record: options.record, state: "pending", thread: recorded.thread};
287
323
  recorded.deliveries = claims;
288
324
  store.writeJsonAtomic(where, file, recorded);
289
325
  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;
290
326
  if (!turn || !turn.id) throw Error("Codex returned no turn identity; claim retained");
291
- claims[key] = {record: options.record, state: "delivered", turn: turn.id};
327
+ Object.assign(claims[key], {state: "delivered", turn: turn.id});
292
328
  store.writeJsonAtomic(where, file, recorded);
293
329
  Object.assign(result, {state: "delivered", turn: turn.id});
294
330
  } else {
@@ -361,4 +397,4 @@ function wakeManaged(where, onlyRole = null) {
361
397
  }
362
398
  return results;
363
399
  }
364
- module.exports = {connect, run, wakeManaged};
400
+ module.exports = {connect, run, wakeManaged, recordedDeliveryState};
@@ -28,11 +28,11 @@ function git(cwd, args, optional = false) {
28
28
  // before 2.36 has no `-z` there (#526: git 2.34 refused it and `keel worktrees`
29
29
  // failed outright), so it falls back to newline-separated fields, which read
30
30
  // every path that holds no newline.
31
- function listWorktrees(repo) {
31
+ function listWorktrees(repo, { optional = false } = {}) {
32
32
  const rows = [];
33
33
  let row = null;
34
34
  const nul = git(repo, ["worktree", "list", "--porcelain", "-z"], true);
35
- const fields = nul !== null ? nul.split("\0") : git(repo, ["worktree", "list", "--porcelain"]).split("\n");
35
+ const fields = nul !== null ? nul.split("\0") : (git(repo, ["worktree", "list", "--porcelain"], optional) || "").split("\n");
36
36
  for (const field of fields) {
37
37
  if (field.startsWith("worktree ")) {
38
38
  row = { path: field.slice(9), branch: null, head: null, locked: null, prunable: null };