@christang/keel 5.231.10 → 5.231.12

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.10",
3
+ "version": "5.231.12",
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.10 -->
1
+ <!-- keel:start version=5.231.12 -->
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,7 @@ Usage:
108
108
  keel worktrees add [--repo <path>] --path <path> --branch <new-branch> [--base <ref>] [--json]
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
+ keel codex list [--repo <path>] [--json] (read local managed role registrations offline)
111
112
  keel codex status|start|deliver|handover|drain|recover [--repo <path>] [--role <role>] [--socket <path>] [--json] (managed Codex roles; explicit host identity)
112
113
  keel codex status [--repo <path>] --role <role> --record <id> [--json] (read the durable delivery receipt locally)
113
114
  keel codex inspect-registration --repo <path> --role <role> --thread <id> --socket <path> --authority <reference>
@@ -3398,7 +3399,8 @@ function main() {
3398
3399
  }
3399
3400
  // `keel chat` likewise: the group chat between sessions (#187).
3400
3401
  if (process.argv[2] === "chat") {
3401
- return require("../src/core/chat/cli").runChat(process.argv.slice(3));
3402
+ Promise.resolve(require("../src/core/chat/cli").runChat(process.argv.slice(3))).then(code => { process.exitCode = code; });
3403
+ return 0;
3402
3404
  }
3403
3405
  // `keel shift` likewise: a coordinated shift change for a role's session.
3404
3406
  if (process.argv[2] === "shift") {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.231.10",
3
+ "version": "5.231.12",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.231.10",
9
+ "version": "5.231.12",
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.10",
5
+ "version": "5.231.12",
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.10",
3
+ "version": "5.231.12",
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.10",
3
+ "version": "5.231.12",
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",
@@ -9,6 +9,63 @@ const fs=require('node:fs');
9
9
  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,['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
+ test('list managed roles offline without draining or changing the shared mailbox', async t => {
13
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'keel-role-list-'));
14
+ t.after(() => fs.rmSync(dir, {recursive: true, force: true}));
15
+ require('node:child_process').execFileSync('git', ['init', '-q', dir]);
16
+ const store = require('../src/core/chat/store');
17
+ const where = store.requireLocation(dir);
18
+ async function list() {
19
+ const result = await run(['--repo', dir, '--json'], 'list');
20
+ assert.equal(result.code, 0, result.err);
21
+ return JSON.parse(result.out).roles;
22
+ }
23
+ assert.deepEqual(await list(), []);
24
+ assert.ok(!fs.existsSync(where.root));
25
+ const socket = path.join(dir, 'host.sock');
26
+ let connections = 0;
27
+ const server = require('node:net').createServer(peer => { connections++; peer.destroy(); });
28
+ await new Promise(resolve => server.listen(socket, resolve));
29
+ t.after(() => new Promise(resolve => server.close(resolve)));
30
+ const registry = path.join(where.root, 'codex-roles');
31
+ fs.mkdirSync(registry, {recursive: true});
32
+ const bindings = {};
33
+ for (const role of ['worker', 'paused', 'moved']) {
34
+ const worktree = path.join(dir, role);
35
+ bindings[worktree] = role === 'moved' ? 'other' : role;
36
+ fs.mkdirSync(worktree);
37
+ fs.writeFileSync(path.join(registry, role + '.json'), JSON.stringify({
38
+ state: 'managed', role, worktree, thread: role + '-thread', socket, deliveries: {private: 'secret'},
39
+ }));
40
+ }
41
+ fs.writeFileSync(path.join(where.root, 'roles.json'), JSON.stringify(bindings));
42
+ store.createGroup(where, 'owner', 'team', ['worker', 'group-only']);
43
+ store.writeRecord(where, {group: 'team', kind: 'todo', from: 'owner', assignee: 'worker', text: 'pending'});
44
+ require('../src/core/chat/notice').park(where, 'paused', 'owner', 'maintenance');
45
+ fs.writeFileSync(path.join(registry, 'broken.json'), '{');
46
+ fs.writeFileSync(path.join(registry, 'broken-new.json'), JSON.stringify({state: 'creation-pending'}));
47
+ function snapshot() {
48
+ return fs.readdirSync(where.root, {recursive: true}).sort().map(name => {
49
+ const file = path.join(where.root, name);
50
+ return [name, fs.statSync(file).isFile() ? fs.readFileSync(file) : null];
51
+ });
52
+ }
53
+ const before = snapshot();
54
+ const rows = await list();
55
+ assert.deepEqual(rows.map(row => row.role), ['broken', 'broken-new', 'moved', 'paused', 'worker']);
56
+ assert.deepEqual(rows[0], {role: 'broken', state: 'invalid', worktree: null, thread: null, socket: null, parked: false, error: 'unreadable-registration'});
57
+ assert.equal(rows[1].error, 'creation-pending');
58
+ assert.equal(rows[2].error, 'binding-mismatch');
59
+ assert.equal(rows[2].state, 'invalid');
60
+ for (const row of rows.slice(3)) {
61
+ assert.deepEqual(row, {role: row.role, state: 'managed', worktree: path.join(dir, row.role),
62
+ thread: row.role + '-thread', socket, parked: row.role === 'paused'});
63
+ }
64
+ assert.deepEqual(await list(), rows);
65
+ assert.deepEqual(snapshot(), before);
66
+ assert.equal(connections, 0);
67
+ });
68
+
12
69
  test('managed CLI lifecycle, mailbox scheduling and frame boundaries',async()=>{
13
70
  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
71
  let observationTurn = null;
@@ -150,7 +207,7 @@ test('managed CLI lifecycle, mailbox scheduling and frame boundaries',async()=>{
150
207
  unloaded=true;let rb=resumes(),tb=turns();
151
208
  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);
152
209
  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);
153
- const resumeRequest=requestDetails.find(x=>x.method==='thread/resume');assert.deepEqual(resumeRequest.params,{threadId:'fixture-thread-2',serviceName:'keel'});
210
+ const resumeRequest=requestDetails.find(x=>x.method==='thread/resume');assert.deepEqual(resumeRequest.params,{threadId:'fixture-thread-2',excludeTurns:true,serviceName:'keel'});
154
211
  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);
155
212
  const unknown=await run(recoveryArgs(uncertainTodo.id),'deliver');assert.notEqual(unknown.code,0);assert.match(unknown.err,/unknown/);assert.equal(resumes(),rb);
156
213
  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;
@@ -231,6 +288,7 @@ async function reviewerHost({onTurnStart}={}) {
231
288
  let serial=0,rejectPersistence=false,mismatch=false,dropStartReply=false;
232
289
  const server=http.createServer();
233
290
  server.on('upgrade',(req,s)=>{
291
+ s.on("error",error => { if (error.code !== "ECONNRESET") throw error; });
234
292
  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');
235
293
  let buf=Buffer.alloc(0), experimentalApi=false;s.on('end',()=>{for(const t of threads.values()){t.loaded=false;t.reviewer=t.savedReviewer;}});
236
294
  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;
@@ -238,16 +296,21 @@ async function reviewerHost({onTurnStart}={}) {
238
296
  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:[]}});
239
297
  if(x.method==='initialize'){experimentalApi=p.capabilities?.experimentalApi===true;result={userAgent:'native-reviewer-fixture'};}
240
298
  else if(x.method==='thread/start'){t={id:'reviewer-'+ ++serial,cwd:p.cwd,reviewer:p.approvalsReviewer||'user',savedReviewer:'user',loaded:true};threads.set(t.id,t);result=reply();}
299
+ else if(x.method==='thread/turns/list')result={data:t.turns || [],nextCursor:null};
300
+ else if(x.method==='thread/items/list')result={data:t.items || [],nextCursor:null};
241
301
  else if(x.method==='thread/name/set'){}
242
302
  else if(x.method==='thread/settings/update'){if(rejectPersistence)error={message:'native reviewer persistence rejected'};else t.savedReviewer=t.reviewer=p.approvalsReviewer;}
243
303
  else if(x.method==='thread/read')result=reply();
244
- else if(x.method==='thread/resume'){if(p.runtimeWorkspaceRoots!==undefined&&!experimentalApi)error={message:'thread/resume.runtimeWorkspaceRoots requires experimentalApi capability'};else 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';}}
304
+ else if(x.method==='thread/resume'){if(p.runtimeWorkspaceRoots!==undefined&&!experimentalApi)error={message:'thread/resume.runtimeWorkspaceRoots requires experimentalApi capability'};else 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.longHistory && !p.excludeTurns)result.thread.turns=[{text:"x".repeat(16*1024*1024)}];if(t.wrongResumeCwd)result.thread.cwd='/wrong-resumed-cwd';}}
245
305
  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}};}
246
306
  else error={message:'unsupported fixture RPC '+x.method};
247
307
  if(dropStartReply&&x.method==='thread/start')continue;
248
308
  const send = (payload = result) => {
249
309
  const body=Buffer.from(JSON.stringify({id:x.id,...error?{error}:{result:payload}}));
250
- const h=body.length<126?Buffer.from([129,body.length]):Buffer.from([129,126,body.length>>8,body.length&255]);
310
+ const h=Buffer.alloc(body.length<126?2:body.length<=65535?4:10);
311
+ h[0]=129;h[1]=h.length===2?body.length:h.length===4?126:127;
312
+ if(h.length===4)h.writeUInt16BE(body.length,2);
313
+ if(h.length===10)h.writeBigUInt64BE(BigInt(body.length),2);
251
314
  if (!s.destroyed) s.write(Buffer.concat([h,body]));
252
315
  };
253
316
  if (x.method === 'turn/start' && onTurnStart) onTurnStart(send);
@@ -382,6 +445,103 @@ else fs.appendFileSync('resumes', JSON.stringify(args) + '\\n');
382
445
  }
383
446
  });
384
447
 
448
+ test('collect an owned reviewer result by todo identity', async () => {
449
+ const h = await reviewerHost();
450
+ try {
451
+ const started = await run(h.args(),'start');
452
+ assert.equal(started.code,0,started.err);
453
+ const thread = JSON.parse(started.out).thread;
454
+ const host = h.threads.get(thread);
455
+ const store = require('../src/core/chat/store');
456
+ const where = store.requireLocation(h.dir);
457
+ store.createGroup(where,'owner','team',['reviewer-worker']);
458
+ const todo = store.writeRecord(where,{group:'team',from:'owner',kind:'todo',assignee:'reviewer-worker',text:'Review fixture'});
459
+ const drain = await run(['--repo',h.dir,'--json'],'drain');
460
+ assert.equal(drain.code,0,drain.err);
461
+ const turn = JSON.parse(drain.out).deliveries[0].turn;
462
+ const collect = () => run(['--repo',h.dir,'show',todo.id,'--collect','--json'],'chat');
463
+ const show = () => run(['--repo',h.dir,'show',todo.id,'--json'],'chat');
464
+ const item = {id:'a1',type:'agentMessage',phase:'final_answer',text:JSON.stringify({taskId:todo.id,result:'reviewed fixture'})};
465
+ host.turns = [{id:turn,status:'completed'}];
466
+ host.items = [{turnId:turn,item}];
467
+ const registry = path.join(where.root,'codex-roles','reviewer-worker.json');
468
+ const original = fs.readFileSync(registry);
469
+ async function refused() {
470
+ const before = fs.readFileSync(registry);
471
+ assert.notEqual((await collect()).code,0);
472
+ assert.deepEqual(fs.readFileSync(registry),before);
473
+ assert.equal(JSON.parse((await show()).out).result,undefined);
474
+ }
475
+ for (const mutate of [
476
+ role => { role.thread = 'successor'; },
477
+ role => { role.handover = {state:'pending'}; },
478
+ role => { role.endpointMigrations = [{plan:'moved'}]; },
479
+ role => { delete Object.values(role.deliveries)[0].resultSource; },
480
+ role => { Object.values(role.deliveries)[0].state = 'pending'; },
481
+ ]) {
482
+ const role = JSON.parse(original);
483
+ mutate(role);
484
+ fs.writeFileSync(registry,JSON.stringify(role));
485
+ await refused();
486
+ }
487
+ fs.writeFileSync(registry,original);
488
+ for (const badItem of [
489
+ {turnId:'other-turn',item},
490
+ {turnId:turn,item:{...item,phase:'commentary'}},
491
+ {turnId:turn,item:{...item,text:JSON.stringify({taskId:'other',result:'unrelated'})}},
492
+ {turnId:turn,item:{...item,type:'commandExecution'}},
493
+ ]) {
494
+ host.items = [badItem];
495
+ await refused();
496
+ }
497
+ host.items = [{turnId:turn,item}];
498
+ host.turns = [{id:turn,status:'inProgress'}];
499
+ await refused();
500
+ host.turns = [{id:turn,status:'completed'}];
501
+ const migration = path.join(where.root,'codex-transitions','fixture.json');
502
+ store.writeJsonAtomic(where,migration,{plan:{role:'reviewer-worker'},state:'pending'});
503
+ await refused();
504
+ fs.unlinkSync(migration);
505
+ const collected = await collect();
506
+ assert.equal(collected.code,0,'owned result collection failed: '+collected.err);
507
+ assert.deepEqual(JSON.parse(collected.out).result,{text:'reviewed fixture',role:'reviewer-worker',thread,turn});
508
+ const shown = JSON.parse((await show()).out);
509
+ assert.deepEqual(shown.result,JSON.parse(collected.out).result);
510
+ assert.equal(shown.task.state,'open');
511
+ const count = h.requests.length;
512
+ assert.equal((await collect()).out,collected.out);
513
+ assert.equal(h.requests.length,count,'a stored result needs no native connection');
514
+ } finally { await h.close(); }
515
+ });
516
+
517
+ test('long native history can resume the original managed role and deduplicate delivery',async () => {
518
+ const h = await reviewerHost();
519
+ try {
520
+ const started = await run(h.args(),'start');
521
+ const original = JSON.parse(started.out).thread;
522
+ const native = h.threads.get(original);
523
+ native.longHistory = true;
524
+ native.loaded = false;
525
+ const args = ['--repo',h.dir,'--role','reviewer-worker','--record','large-history-card','--text','Review','--json'];
526
+ const first = await run(args,'deliver');
527
+ assert.equal(first.code,0,first.err);
528
+ const again = await run(args,'deliver');
529
+ assert.equal(again.code,0,again.err);
530
+ assert.equal(JSON.parse(again.out).turn,JSON.parse(first.out).turn);
531
+ assert.equal(h.requests.filter(r=>r.method==='turn/start').length,1);
532
+ assert.equal(h.threads.size,1);
533
+ assert.equal(h.requests.find(r=>r.method==='thread/resume').params.threadId,original);
534
+ assert.deepEqual(h.turnReviewers,['auto_review']);
535
+ native.cwd = '/old-worktree';
536
+ native.loaded = false;
537
+ const recovered = await run(['--repo',h.dir,'--role','reviewer-worker','--json'],'recover');
538
+ assert.equal(recovered.code,0,recovered.err);
539
+ assert.equal(JSON.parse(recovered.out).thread,original);
540
+ assert.equal(native.cwd,h.dir);
541
+ assert.equal(h.requests.filter(r=>r.method==='turn/start').length,1);
542
+ } finally { await h.close(); }
543
+ });
544
+
385
545
  test('explicit thread reviewer persists before managed success without a model turn',async()=>{
386
546
  const h=await reviewerHost();try{
387
547
  const r=await run(h.args(),'start');assert.equal(r.code,0,r.err);
@@ -71,7 +71,7 @@ test('register original readonly frontend and deliver with unchanged policy',asy
71
71
  const delivered=await run('deliver',args);assert.equal(delivered.code,0,delivered.err);assert.equal(JSON.parse(delivered.out).state,'delivered');
72
72
  const duplicate=await run('deliver',args);assert.equal(duplicate.code,0,duplicate.err);assert.equal(JSON.parse(duplicate.out).state,'already-delivered');
73
73
  assert.equal(h.requests.filter(x=>x.method==='turn/start').length,1);assert.deepEqual(h.native.policy,entry.nativePolicy);
74
- 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');
74
+ const resumed=h.requests.filter(x=>x.method==='thread/resume');assert.ok(resumed.every(x=>Object.keys(x.params).every(key=>key==='threadId'||(key==='excludeTurns'&&x.params.excludeTurns===true))),'no permission overrides while inspecting or delivering registered frontend');
75
75
  }finally{await h.close();}
76
76
  });
77
77
 
@@ -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"), str(ROOT / "scripts/test_codex_onboarding.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=120)
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.231.10"
38
+ PACKAGE_VERSION = "5.231.12"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.231.10"
41
+ PROTOCOL_VERSION = "5.231.12"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -556,11 +556,29 @@ def validate_branch_lock_race_scenario() -> int:
556
556
  label = "branch-lock-race:"
557
557
  with tempfile.TemporaryDirectory(prefix="keel-branch-race-") as raw:
558
558
  d = _Devices(Path(raw).resolve())
559
+ # Hold each clone at its first push until both have observed the free
560
+ # ref. Merely starting both commands can instead test a later acquire
561
+ # of an already-held lock when one process is scheduled late.
562
+ for own, peer in ((d.a, d.b), (d.b, d.a)):
563
+ hook = own / ".git" / "hooks" / "pre-push"
564
+ write_text(hook, "#!/usr/bin/env python3\nfrom pathlib import Path\nimport time\n"
565
+ f"Path({str(d.base / (own.name + '.ready'))!r}).touch()\n"
566
+ f"peer = Path({str(d.base / (peer.name + '.ready'))!r})\n"
567
+ "deadline = time.monotonic() + 30\n"
568
+ "while not peer.exists() and time.monotonic() < deadline: time.sleep(0.02)\n"
569
+ "raise SystemExit(0 if peer.exists() else 1)\n")
570
+ hook.chmod(0o755)
571
+ d.git(own, "config", "core.hooksPath", str(hook.parent))
559
572
  procs = [subprocess.Popen(["node", str(Path(__file__).resolve().parents[2] / "bin" / "keel.js"),
560
573
  "lock", "acquire", "--branch", "feat"], cwd=path, env=d.env(path),
561
574
  stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
562
575
  for path in (d.a, d.b)]
563
576
  results = [(proc, *proc.communicate(timeout=120)) for proc in procs]
577
+ for clone in (d.a, d.b):
578
+ (clone / ".git" / "hooks" / "pre-push").unlink()
579
+ if not (d.base / (clone.name + ".ready")).exists():
580
+ report(f"{label} the two contenders did not reach the push together.")
581
+ return 1
564
582
  codes = sorted(proc.returncode for proc, _, _ in results)
565
583
  if codes != [0, 1]:
566
584
  report(f"{label} `keel lock acquire --branch feat` from two devices should give one 0 and one 1, got "
@@ -32,7 +32,7 @@ const USAGE = [
32
32
  "keel chat <group> [--since <90s|15m|2h|3d|date>] [--follow] [--peek] [--json] (view; advances your read position unless --peek)",
33
33
  "keel chat unread [--json]",
34
34
  "keel chat read [<group>] [--json]",
35
- "keel chat show <id> [--json]",
35
+ "keel chat show <id> [--json] [--collect]",
36
36
  "keel chat todo <group> --assignee <role> [--issue <n>] <text...> [--json]",
37
37
  "keel chat todos [<group>] [--mine] [--json]",
38
38
  "keel chat done <id>",
@@ -82,7 +82,7 @@ const VALUED = {
82
82
  "--compact-at": "compactAt",
83
83
  };
84
84
  const REPEATED = { "--member": "members" };
85
- const SWITCHES = { "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail", "--check": "check", "--ack": "ack", "--no-wake": "noWake", "--listen": "listen", "--closed": "closed", "--stamp": "stamp", "--no-stamp": "noStamp", "--help": "help", "-h": "help", "--prune": "prune", "--unset": "unset", "--leave-branches": "leaveBranches" };
85
+ const SWITCHES = { "--collect": "collect", "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail", "--check": "check", "--ack": "ack", "--no-wake": "noWake", "--listen": "listen", "--closed": "closed", "--stamp": "stamp", "--no-stamp": "noStamp", "--help": "help", "-h": "help", "--prune": "prune", "--unset": "unset", "--leave-branches": "leaveBranches" };
86
86
 
87
87
  function parseChatArgs(argv) {
88
88
  const options = { positionals: [], members: [], json: false, peek: false, all: false, mine: false, follow: false, once: false, mail: false, check: false, ack: false, noWake: false, listen: false, closed: false, stamp: false, noStamp: false, help: false, prune: false, unset: false, leaveBranches: false };
@@ -489,8 +489,15 @@ function dispatch(where, options) {
489
489
  case "show": {
490
490
  const id = rest[0];
491
491
  if (!id) throw new ChatError("keel chat show needs a record id.");
492
+ if (options.collect && path.basename(id) !== id) throw new ChatError("Invalid todo ID.");
492
493
  const record = store.findRecord(where, id);
493
494
  if (!record) throw new ChatError(`No record ${id}.`);
495
+ if (options.collect) {
496
+ if (record.kind !== "todo" || record.id !== id) throw new ChatError("--collect requires an original todo ID");
497
+ return require("../codex-host").collectTaskResult(where, record)
498
+ .then(() => dispatch(where, {...options, collect:false}))
499
+ .catch(error => { process.stderr.write(`keel chat: ${error.message}\n`); return 2; });
500
+ }
494
501
  const readers = store.readersOf(where, record);
495
502
  const acks = record.ack === "requested" ? store.ackStatus(where, record) : null;
496
503
  if (options.json) {
@@ -498,8 +505,9 @@ function dispatch(where, options) {
498
505
  if (record.kind === "todo") {
499
506
  const closure = store.todoClosure(where, record);
500
507
  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) };
508
+ const delivery = require("../codex-host").recordedDelivery(where, record.assignee, record.id);
509
+ result.delivery = {state: delivery.state};
510
+ if (delivery.result) result.result = delivery.result;
503
511
  }
504
512
  out(JSON.stringify(result));
505
513
  } else out([`${record.group} ${formatLine(record)}`, `read by: ${readers.join(", ") || "nobody yet"}`, ...(acks ? ackLines(acks) : [])].join("\n"));
@@ -750,6 +758,9 @@ function runWake(cwd, options) {
750
758
  function runChat(argv) {
751
759
  try {
752
760
  const options = parseChatArgs(argv);
761
+ if (options.collect && (options.positionals[0] !== "show" || options.positionals.length !== 2 || !options.json)) {
762
+ throw new ChatError("--collect requires chat show <todo-id> --json");
763
+ }
753
764
  const cwd = path.resolve(options.repo || process.cwd());
754
765
  if (!options.positionals.length || options.positionals[0] === "help" || options.help) {
755
766
  out(`Usage:\n ${USAGE.join("\n ")}`);
@@ -131,19 +131,19 @@ function deliveryReceipt(role, record) {
131
131
  return { role: role.role, record, state, thread, turn };
132
132
  }
133
133
 
134
- function recordedDeliveryState(where, assignee, record) {
134
+ function recordedDelivery(where, assignee, record) {
135
135
  const fs = require("node:fs");
136
136
  const store = require("./chat/store");
137
137
  try {
138
138
  store.checkName(assignee, "Assignee");
139
139
  const file = path.join(where.root, "codex-roles", `${assignee}.json`);
140
140
  const role = JSON.parse(fs.readFileSync(file, "utf8"));
141
- if (role?.role !== assignee || role.state !== "managed") return "unknown";
141
+ if (role?.role !== assignee || role.state !== "managed") return {state: "unknown"};
142
142
  const receipt = deliveryReceipt(role, record);
143
- if (receipt.state === "delivered") return "acknowledged";
144
- return receipt.state === "unrecorded" ? "unobserved" : "unknown";
143
+ if (receipt.state === "delivered") return {state: "acknowledged", result: role.deliveries[deliveryKey(record)].result};
144
+ return {state: receipt.state === "unrecorded" ? "unobserved" : "unknown"};
145
145
  } catch (error) {
146
- return error.code === "ENOENT" ? "unobserved" : "unknown";
146
+ return {state: error.code === "ENOENT" ? "unobserved" : "unknown"};
147
147
  }
148
148
  }
149
149
 
@@ -176,6 +176,46 @@ async function findObservedTurn(client, receipt, timeout) {
176
176
  }
177
177
  }
178
178
 
179
+ // Pull only from the recorded native execution. The role lock is shared with
180
+ // delivery, handover, recover and migration. An accepted receipt is immutable.
181
+ async function collectTaskResult(where, todo) {
182
+ const fs = require("node:fs");
183
+ const store = require("./chat/store");
184
+ const {currentTodo, migrationPending, readFinalResult} = require("./managed-task-result");
185
+ store.checkName(todo.assignee, "Assignee");
186
+ const file = path.join(where.root, "codex-roles", todo.assignee + ".json");
187
+ if (!fs.existsSync(file)) throw Error("task has no managed delivery");
188
+ const lock = file + ".lock";
189
+ const fd = fs.openSync(lock, "wx");
190
+ let client;
191
+ try {
192
+ const original = fs.readFileSync(file, "utf8");
193
+ const role = JSON.parse(original);
194
+ if (role.state !== "managed" || role.role !== todo.assignee) throw Error("managed role mismatch");
195
+ const receipt = deliveryReceipt(role, todo.id);
196
+ const claim = role.deliveries?.[deliveryKey(todo.id)];
197
+ if (receipt.state !== "delivered" || !claim.resultSource) throw Error("no result-enabled delivery receipt");
198
+ if (claim.result) return;
199
+ if (role.handover || receipt.thread !== role.thread || claim.resultSource.socket !== role.socket ||
200
+ claim.resultSource.migrations !== (role.endpointMigrations?.length || 0) ||
201
+ migrationPending(where, role.role) || !currentTodo(where, role, todo.id)) throw Error("task execution no longer owns result submission");
202
+ client = await connect(role.socket);
203
+ await initializeClient(client, true);
204
+ const {thread} = await client.call("thread/read", {threadId: receipt.thread, includeTurns: false});
205
+ if (thread?.id !== receipt.thread || thread.cwd !== role.worktree) throw Error("native result owner mismatch");
206
+ const turn = await findObservedTurn(client, receipt, 5000);
207
+ if (turn?.status !== "completed") throw Error("original turn has no verified completion");
208
+ const result = await readFinalResult(client, receipt);
209
+ if (fs.readFileSync(file, "utf8") !== original || !currentTodo(where, role, todo.id)) throw Error("task assignment changed while collecting");
210
+ claim.result = result;
211
+ store.writeJsonAtomic(where, file, role);
212
+ } finally {
213
+ client?.close();
214
+ fs.closeSync(fd);
215
+ fs.unlinkSync(lock);
216
+ }
217
+ }
218
+
179
219
  async function observeDelivery(receipt, role, timeout) {
180
220
  const observation = {state: "unknown", backgroundTerminals: "unknown"};
181
221
  if (receipt.state !== "delivered" || !receipt.thread || !receipt.turn) return observation;
@@ -204,6 +244,45 @@ async function observeDelivery(receipt, role, timeout) {
204
244
  return observation;
205
245
  }
206
246
 
247
+ function listManagedRoles(where) {
248
+ const fs = require('node:fs');
249
+ const store = require('./chat/store');
250
+ const {parkOf} = require('./chat/notice');
251
+ const directory = path.join(where.root, 'codex-roles');
252
+ let files;
253
+ try {
254
+ files = fs.readdirSync(directory, {withFileTypes: true});
255
+ } catch (error) {
256
+ if (error.code === 'ENOENT') return [];
257
+ throw error;
258
+ }
259
+ const bindings = store.readRoles(where.root);
260
+ const rows = files.filter(file => file.name.endsWith('.json')).map(file => {
261
+ const role = file.name.slice(0, -5);
262
+ const row = {role, state: 'invalid', worktree: null, thread: null, socket: null, parked: !!parkOf(where, role)};
263
+ let entry;
264
+ try {
265
+ if (!file.isFile()) return {...row, error: 'unreadable-registration'};
266
+ entry = JSON.parse(fs.readFileSync(path.join(directory, file.name), 'utf8'));
267
+ } catch {
268
+ return {...row, error: 'unreadable-registration'};
269
+ }
270
+ for (const key of ['worktree', 'thread', 'socket']) {
271
+ if (typeof entry?.[key] === 'string' && entry[key]) row[key] = entry[key];
272
+ }
273
+ if (entry?.state === 'creation-pending') return {...row, error: 'creation-pending'};
274
+ if (entry?.state !== 'managed' || entry.role !== role || !row.worktree || !row.thread || !row.socket) {
275
+ return {...row, error: 'invalid-registration'};
276
+ }
277
+ if (bindings[row.worktree] !== role || Object.values(bindings).filter(value => value === role).length !== 1) {
278
+ return {...row, error: 'binding-mismatch'};
279
+ }
280
+ row.state = 'managed';
281
+ return row;
282
+ });
283
+ return rows.sort((a, b) => a.role < b.role ? -1 : a.role > b.role ? 1 : 0);
284
+ }
285
+
207
286
  async function run(args) {
208
287
  const onboarding = require("./codex-onboarding");
209
288
  if (onboarding.actions.includes(args[0])) return onboarding.run(args, {connect});
@@ -213,12 +292,13 @@ async function run(args) {
213
292
  let registrationLock;
214
293
  try {
215
294
  const action = args.shift();
216
- 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]");
295
+ if (!["list", "status", "start", "deliver", "handover", "drain", "recover"].includes(action)) throw Error("Usage: keel codex list|status|start|deliver|handover|drain|recover [--socket path] [--role name] [--repo path] [--thread id] [--timeout ms] [--json]");
217
296
  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()};
218
297
  let explicitSocket = false;
219
298
  let explicitTimeout = false;
220
299
  while (args.length) {
221
300
  const flag = args.shift();
301
+ if (action === "list" && !["--repo", "--json"].includes(flag)) throw Error("Usage: keel codex list [--repo path] [--json]");
222
302
  if (flag === "--json") options.json = true;
223
303
  else if (flag === "--observe") options.observe = true;
224
304
  else if (["--socket", "--thread", "--timeout", "--role", "--repo", "--record", "--text", "--note", "--approvals-reviewer"].includes(flag)) {
@@ -239,6 +319,11 @@ async function run(args) {
239
319
  if (!Number.isInteger(ms) || ms < 50 || ms > 60000) throw Error("timeout must be 50–60000 milliseconds");
240
320
  const fs = require("node:fs");
241
321
  const store = require("./chat/store");
322
+ if (action === "list") {
323
+ const roles = listManagedRoles(store.requireLocation(path.resolve(options.repo)));
324
+ process.stdout.write(JSON.stringify({roles}) + "\n");
325
+ return 0;
326
+ }
242
327
  if (action === "drain") {
243
328
  const deliveries = await wakeManaged(store.requireLocation(path.resolve(options.repo)), options.role);
244
329
  process.stdout.write(JSON.stringify({deliveries}) + "\n");
@@ -340,7 +425,7 @@ async function run(args) {
340
425
  } else {
341
426
  // Native writer ownership decides whether the original id can resume.
342
427
  // Restore only the recorded execution cwd; never rewrite role claims.
343
- 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));
428
+ const resumed = await client.call("thread/resume", {threadId: recorded.thread, excludeTurns: true, 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));
344
429
  if (!resumed.thread || resumed.thread.id !== recorded.thread || resumed.thread.cwd !== recorded.worktree) throw Error("recovered managed role identity mismatch; original registry retained");
345
430
  if (savedPolicy) onboarding.verifyPolicy(resumed, savedPolicy);
346
431
  else if (resumed.approvalPolicy !== "on-request") throw Error("recovered thread approval policy mismatch; original registry retained");
@@ -367,7 +452,7 @@ async function run(args) {
367
452
  // connection alive through the subsequent turn/start and preserve
368
453
  // saved sandbox/approval settings. An explicitly chosen reviewer
369
454
  // belongs to the managed role and follows its later deliveries.
370
- const resumed = await client.call("thread/resume", {threadId: recorded.thread, ...(!savedPolicy ? {serviceName: "keel", ...(recorded.approvalsReviewer ? {approvalsReviewer: recorded.approvalsReviewer} : {})} : {})}, explicitTimeout ? ms : Math.max(ms, 15000));
455
+ const resumed = await client.call("thread/resume", {threadId: recorded.thread, excludeTurns: true, ...(!savedPolicy ? {serviceName: "keel", ...(recorded.approvalsReviewer ? {approvalsReviewer: recorded.approvalsReviewer} : {})} : {})}, explicitTimeout ? ms : Math.max(ms, 15000));
371
456
  thread = resumed.thread;
372
457
  if (!owned(thread)) throw Error("resumed managed role identity mismatch");
373
458
  if (thread.status?.type === "idle") {
@@ -382,9 +467,15 @@ async function run(args) {
382
467
  Object.assign(result, {state: "waiting", thread: recorded.thread});
383
468
  } else if (action === "deliver") {
384
469
  claims[key] = {record: options.record, state: "pending", thread: recorded.thread};
470
+ let prompt = options.text;
471
+ if (require("./managed-task-result").currentTodo(where, recorded, options.record)) {
472
+ claims[key].resultSource = {socket: recorded.socket, migrations: recorded.endpointMigrations?.length || 0};
473
+ prompt += "\nTo return a result without writing the mailbox, use this JSON object as your entire final answer, replacing the placeholder with your report: " +
474
+ JSON.stringify({taskId: options.record, result: "<report>"});
475
+ }
385
476
  recorded.deliveries = claims;
386
477
  store.writeJsonAtomic(where, file, recorded);
387
- 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;
478
+ 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` : "") + prompt}]})).turn;
388
479
  if (!turn || !turn.id) throw Error("Codex returned no turn identity; claim retained");
389
480
  Object.assign(claims[key], {state: "delivered", turn: turn.id});
390
481
  store.writeJsonAtomic(where, file, recorded);
@@ -480,4 +571,4 @@ async function wakeManaged(where, onlyRole = null) {
480
571
  }));
481
572
  return results.flat();
482
573
  }
483
- module.exports = {connect, run, wakeManaged, recordedDeliveryState};
574
+ module.exports = {connect, run, wakeManaged, recordedDelivery, collectTaskResult};
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ const fs = require("node:fs");
3
+ const path = require("node:path");
4
+ const store = require("./chat/store");
5
+
6
+ // Eligibility is derived from durable state. A text argument, role environment
7
+ // variable or model-supplied identity cannot designate a different assignment.
8
+ function currentTodo(where, role, id) {
9
+ if (!id || path.basename(id) !== id) return false;
10
+ const todo = store.findRecord(where, id);
11
+ if (!todo || todo.id !== id || todo.kind !== "todo" || todo.assignee !== role.role) return false;
12
+ const bindings = Object.entries(store.readRoles(where.root)).filter(([, name]) => name === role.role);
13
+ if (bindings.length !== 1 || bindings[0][0] !== role.worktree) return false;
14
+ const log = store.readLog(where, todo.group);
15
+ const group = store.groupState(log);
16
+ return !group.archived && group.members.has(role.role) && !group.listeners.has(role.role)
17
+ && !log.some(record => record.supersedes === id ||
18
+ (record.target === id && ["done", "edit", "retract"].includes(record.kind)));
19
+ }
20
+
21
+ function migrationPending(where, role) {
22
+ const dir = path.join(where.root, "codex-transitions");
23
+ if (!fs.existsSync(dir)) return false;
24
+ return fs.readdirSync(dir).filter(name => name.endsWith(".json")).some(name => {
25
+ const journal = JSON.parse(fs.readFileSync(path.join(dir, name), "utf8"));
26
+ return journal.plan.role === role && journal.state !== "committed";
27
+ });
28
+ }
29
+
30
+ async function readFinalResult(client, receipt) {
31
+ const page = await client.call("thread/items/list", {
32
+ threadId: receipt.thread, turnId: receipt.turn, sortDirection: "desc", limit: 1,
33
+ });
34
+ const entry = page?.data?.[0];
35
+ const item = entry?.item;
36
+ if (page?.data?.length !== 1 || entry.turnId !== receipt.turn || item?.type !== "agentMessage" ||
37
+ item.phase !== "final_answer" || typeof item.text !== "string") throw Error("no designated final answer");
38
+ let envelope;
39
+ try { envelope = JSON.parse(item.text); } catch { throw Error("no task result envelope"); }
40
+ if (envelope?.taskId !== receipt.record || typeof envelope.result !== "string" || !envelope.result.trim()) {
41
+ throw Error("result envelope does not match this task");
42
+ }
43
+ return {text: envelope.result, role: receipt.role, thread: receipt.thread, turn: receipt.turn};
44
+ }
45
+
46
+ module.exports = {currentTodo, migrationPending, readFinalResult};