@christang/keel 5.231.10 → 5.231.11

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.11",
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.11 -->
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
@@ -3398,7 +3398,8 @@ function main() {
3398
3398
  }
3399
3399
  // `keel chat` likewise: the group chat between sessions (#187).
3400
3400
  if (process.argv[2] === "chat") {
3401
- return require("../src/core/chat/cli").runChat(process.argv.slice(3));
3401
+ Promise.resolve(require("../src/core/chat/cli").runChat(process.argv.slice(3))).then(code => { process.exitCode = code; });
3402
+ return 0;
3402
3403
  }
3403
3404
  // `keel shift` likewise: a coordinated shift change for a role's session.
3404
3405
  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.11",
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.11",
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.11",
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.11",
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.11",
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",
@@ -150,7 +150,7 @@ test('managed CLI lifecycle, mailbox scheduling and frame boundaries',async()=>{
150
150
  unloaded=true;let rb=resumes(),tb=turns();
151
151
  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
152
  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'});
153
+ const resumeRequest=requestDetails.find(x=>x.method==='thread/resume');assert.deepEqual(resumeRequest.params,{threadId:'fixture-thread-2',excludeTurns:true,serviceName:'keel'});
154
154
  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
155
  const unknown=await run(recoveryArgs(uncertainTodo.id),'deliver');assert.notEqual(unknown.code,0);assert.match(unknown.err,/unknown/);assert.equal(resumes(),rb);
156
156
  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 +231,7 @@ async function reviewerHost({onTurnStart}={}) {
231
231
  let serial=0,rejectPersistence=false,mismatch=false,dropStartReply=false;
232
232
  const server=http.createServer();
233
233
  server.on('upgrade',(req,s)=>{
234
+ s.on("error",error => { if (error.code !== "ECONNRESET") throw error; });
234
235
  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
236
  let buf=Buffer.alloc(0), experimentalApi=false;s.on('end',()=>{for(const t of threads.values()){t.loaded=false;t.reviewer=t.savedReviewer;}});
236
237
  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 +239,21 @@ async function reviewerHost({onTurnStart}={}) {
238
239
  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
240
  if(x.method==='initialize'){experimentalApi=p.capabilities?.experimentalApi===true;result={userAgent:'native-reviewer-fixture'};}
240
241
  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();}
242
+ else if(x.method==='thread/turns/list')result={data:t.turns || [],nextCursor:null};
243
+ else if(x.method==='thread/items/list')result={data:t.items || [],nextCursor:null};
241
244
  else if(x.method==='thread/name/set'){}
242
245
  else if(x.method==='thread/settings/update'){if(rejectPersistence)error={message:'native reviewer persistence rejected'};else t.savedReviewer=t.reviewer=p.approvalsReviewer;}
243
246
  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';}}
247
+ 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
248
  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
249
  else error={message:'unsupported fixture RPC '+x.method};
247
250
  if(dropStartReply&&x.method==='thread/start')continue;
248
251
  const send = (payload = result) => {
249
252
  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]);
253
+ const h=Buffer.alloc(body.length<126?2:body.length<=65535?4:10);
254
+ h[0]=129;h[1]=h.length===2?body.length:h.length===4?126:127;
255
+ if(h.length===4)h.writeUInt16BE(body.length,2);
256
+ if(h.length===10)h.writeBigUInt64BE(BigInt(body.length),2);
251
257
  if (!s.destroyed) s.write(Buffer.concat([h,body]));
252
258
  };
253
259
  if (x.method === 'turn/start' && onTurnStart) onTurnStart(send);
@@ -382,6 +388,103 @@ else fs.appendFileSync('resumes', JSON.stringify(args) + '\\n');
382
388
  }
383
389
  });
384
390
 
391
+ test('collect an owned reviewer result by todo identity', async () => {
392
+ const h = await reviewerHost();
393
+ try {
394
+ const started = await run(h.args(),'start');
395
+ assert.equal(started.code,0,started.err);
396
+ const thread = JSON.parse(started.out).thread;
397
+ const host = h.threads.get(thread);
398
+ const store = require('../src/core/chat/store');
399
+ const where = store.requireLocation(h.dir);
400
+ store.createGroup(where,'owner','team',['reviewer-worker']);
401
+ const todo = store.writeRecord(where,{group:'team',from:'owner',kind:'todo',assignee:'reviewer-worker',text:'Review fixture'});
402
+ const drain = await run(['--repo',h.dir,'--json'],'drain');
403
+ assert.equal(drain.code,0,drain.err);
404
+ const turn = JSON.parse(drain.out).deliveries[0].turn;
405
+ const collect = () => run(['--repo',h.dir,'show',todo.id,'--collect','--json'],'chat');
406
+ const show = () => run(['--repo',h.dir,'show',todo.id,'--json'],'chat');
407
+ const item = {id:'a1',type:'agentMessage',phase:'final_answer',text:JSON.stringify({taskId:todo.id,result:'reviewed fixture'})};
408
+ host.turns = [{id:turn,status:'completed'}];
409
+ host.items = [{turnId:turn,item}];
410
+ const registry = path.join(where.root,'codex-roles','reviewer-worker.json');
411
+ const original = fs.readFileSync(registry);
412
+ async function refused() {
413
+ const before = fs.readFileSync(registry);
414
+ assert.notEqual((await collect()).code,0);
415
+ assert.deepEqual(fs.readFileSync(registry),before);
416
+ assert.equal(JSON.parse((await show()).out).result,undefined);
417
+ }
418
+ for (const mutate of [
419
+ role => { role.thread = 'successor'; },
420
+ role => { role.handover = {state:'pending'}; },
421
+ role => { role.endpointMigrations = [{plan:'moved'}]; },
422
+ role => { delete Object.values(role.deliveries)[0].resultSource; },
423
+ role => { Object.values(role.deliveries)[0].state = 'pending'; },
424
+ ]) {
425
+ const role = JSON.parse(original);
426
+ mutate(role);
427
+ fs.writeFileSync(registry,JSON.stringify(role));
428
+ await refused();
429
+ }
430
+ fs.writeFileSync(registry,original);
431
+ for (const badItem of [
432
+ {turnId:'other-turn',item},
433
+ {turnId:turn,item:{...item,phase:'commentary'}},
434
+ {turnId:turn,item:{...item,text:JSON.stringify({taskId:'other',result:'unrelated'})}},
435
+ {turnId:turn,item:{...item,type:'commandExecution'}},
436
+ ]) {
437
+ host.items = [badItem];
438
+ await refused();
439
+ }
440
+ host.items = [{turnId:turn,item}];
441
+ host.turns = [{id:turn,status:'inProgress'}];
442
+ await refused();
443
+ host.turns = [{id:turn,status:'completed'}];
444
+ const migration = path.join(where.root,'codex-transitions','fixture.json');
445
+ store.writeJsonAtomic(where,migration,{plan:{role:'reviewer-worker'},state:'pending'});
446
+ await refused();
447
+ fs.unlinkSync(migration);
448
+ const collected = await collect();
449
+ assert.equal(collected.code,0,'owned result collection failed: '+collected.err);
450
+ assert.deepEqual(JSON.parse(collected.out).result,{text:'reviewed fixture',role:'reviewer-worker',thread,turn});
451
+ const shown = JSON.parse((await show()).out);
452
+ assert.deepEqual(shown.result,JSON.parse(collected.out).result);
453
+ assert.equal(shown.task.state,'open');
454
+ const count = h.requests.length;
455
+ assert.equal((await collect()).out,collected.out);
456
+ assert.equal(h.requests.length,count,'a stored result needs no native connection');
457
+ } finally { await h.close(); }
458
+ });
459
+
460
+ test('long native history can resume the original managed role and deduplicate delivery',async () => {
461
+ const h = await reviewerHost();
462
+ try {
463
+ const started = await run(h.args(),'start');
464
+ const original = JSON.parse(started.out).thread;
465
+ const native = h.threads.get(original);
466
+ native.longHistory = true;
467
+ native.loaded = false;
468
+ const args = ['--repo',h.dir,'--role','reviewer-worker','--record','large-history-card','--text','Review','--json'];
469
+ const first = await run(args,'deliver');
470
+ assert.equal(first.code,0,first.err);
471
+ const again = await run(args,'deliver');
472
+ assert.equal(again.code,0,again.err);
473
+ assert.equal(JSON.parse(again.out).turn,JSON.parse(first.out).turn);
474
+ assert.equal(h.requests.filter(r=>r.method==='turn/start').length,1);
475
+ assert.equal(h.threads.size,1);
476
+ assert.equal(h.requests.find(r=>r.method==='thread/resume').params.threadId,original);
477
+ assert.deepEqual(h.turnReviewers,['auto_review']);
478
+ native.cwd = '/old-worktree';
479
+ native.loaded = false;
480
+ const recovered = await run(['--repo',h.dir,'--role','reviewer-worker','--json'],'recover');
481
+ assert.equal(recovered.code,0,recovered.err);
482
+ assert.equal(JSON.parse(recovered.out).thread,original);
483
+ assert.equal(native.cwd,h.dir);
484
+ assert.equal(h.requests.filter(r=>r.method==='turn/start').length,1);
485
+ } finally { await h.close(); }
486
+ });
487
+
385
488
  test('explicit thread reviewer persists before managed success without a model turn',async()=>{
386
489
  const h=await reviewerHost();try{
387
490
  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.11"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.231.10"
41
+ PROTOCOL_VERSION = "5.231.11"
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;
@@ -340,7 +380,7 @@ async function run(args) {
340
380
  } else {
341
381
  // Native writer ownership decides whether the original id can resume.
342
382
  // 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));
383
+ 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
384
  if (!resumed.thread || resumed.thread.id !== recorded.thread || resumed.thread.cwd !== recorded.worktree) throw Error("recovered managed role identity mismatch; original registry retained");
345
385
  if (savedPolicy) onboarding.verifyPolicy(resumed, savedPolicy);
346
386
  else if (resumed.approvalPolicy !== "on-request") throw Error("recovered thread approval policy mismatch; original registry retained");
@@ -367,7 +407,7 @@ async function run(args) {
367
407
  // connection alive through the subsequent turn/start and preserve
368
408
  // saved sandbox/approval settings. An explicitly chosen reviewer
369
409
  // 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));
410
+ 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
411
  thread = resumed.thread;
372
412
  if (!owned(thread)) throw Error("resumed managed role identity mismatch");
373
413
  if (thread.status?.type === "idle") {
@@ -382,9 +422,15 @@ async function run(args) {
382
422
  Object.assign(result, {state: "waiting", thread: recorded.thread});
383
423
  } else if (action === "deliver") {
384
424
  claims[key] = {record: options.record, state: "pending", thread: recorded.thread};
425
+ let prompt = options.text;
426
+ if (require("./managed-task-result").currentTodo(where, recorded, options.record)) {
427
+ claims[key].resultSource = {socket: recorded.socket, migrations: recorded.endpointMigrations?.length || 0};
428
+ prompt += "\nTo return a result without writing the mailbox, use this JSON object as your entire final answer, replacing the placeholder with your report: " +
429
+ JSON.stringify({taskId: options.record, result: "<report>"});
430
+ }
385
431
  recorded.deliveries = claims;
386
432
  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;
433
+ 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
434
  if (!turn || !turn.id) throw Error("Codex returned no turn identity; claim retained");
389
435
  Object.assign(claims[key], {state: "delivered", turn: turn.id});
390
436
  store.writeJsonAtomic(where, file, recorded);
@@ -480,4 +526,4 @@ async function wakeManaged(where, onlyRole = null) {
480
526
  }));
481
527
  return results.flat();
482
528
  }
483
- module.exports = {connect, run, wakeManaged, recordedDeliveryState};
529
+ 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};