@christang/keel 5.231.5 → 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.
- package/.claude-plugin/plugin.json +1 -1
- package/assets/bootstrap/AGENTS.md +1 -1
- package/bin/keel.js +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/plugins/keel/.claude-plugin/plugin.json +1 -1
- package/plugins/keel/.codex-plugin/plugin.json +1 -1
- package/plugins/keel/hooks/codex.json +8 -4
- package/plugins/keel/scripts/pretooluse-guard.js +1 -1
- package/plugins/keel/scripts/session-start.js +1 -1
- package/scripts/test_codex_host.js +59 -4
- package/scripts/validate_codex_receiving.py +88 -1
- package/scripts/validation/common.py +2 -2
- package/src/core/branches.js +3 -3
- package/src/core/chat/cli.js +2 -0
- package/src/core/codex-host.js +40 -4
- package/src/core/worktrees.js +2 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.231.
|
|
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",
|
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>
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@christang/keel",
|
|
3
|
-
"version": "5.231.
|
|
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.
|
|
9
|
+
"version": "5.231.7",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@fission-ai/openspec": "1.14.0"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.231.
|
|
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.
|
|
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",
|
|
@@ -7,12 +7,14 @@
|
|
|
7
7
|
{
|
|
8
8
|
"type": "command",
|
|
9
9
|
"command": "node \"${PLUGIN_ROOT}/scripts/session-start.js\"",
|
|
10
|
-
"timeout": 15
|
|
10
|
+
"timeout": 15,
|
|
11
|
+
"statusMessage": "Keel: Session context"
|
|
11
12
|
},
|
|
12
13
|
{
|
|
13
14
|
"type": "command",
|
|
14
15
|
"command": "node \"${PLUGIN_ROOT}/scripts/codex-mail-hook.js\" session-start",
|
|
15
|
-
"timeout": 10
|
|
16
|
+
"timeout": 10,
|
|
17
|
+
"statusMessage": "Keel: Mail at session start"
|
|
16
18
|
}
|
|
17
19
|
]
|
|
18
20
|
}
|
|
@@ -24,7 +26,8 @@
|
|
|
24
26
|
{
|
|
25
27
|
"type": "command",
|
|
26
28
|
"command": "node \"${PLUGIN_ROOT}/scripts/pretooluse-guard.js\"",
|
|
27
|
-
"timeout": 10
|
|
29
|
+
"timeout": 10,
|
|
30
|
+
"statusMessage": "Keel: Write guard"
|
|
28
31
|
}
|
|
29
32
|
]
|
|
30
33
|
}
|
|
@@ -35,7 +38,8 @@
|
|
|
35
38
|
{
|
|
36
39
|
"type": "command",
|
|
37
40
|
"command": "node \"${PLUGIN_ROOT}/scripts/codex-mail-hook.js\" user-prompt-submit",
|
|
38
|
-
"timeout": 10
|
|
41
|
+
"timeout": 10,
|
|
42
|
+
"statusMessage": "Keel: Mail before prompt"
|
|
39
43
|
}
|
|
40
44
|
]
|
|
41
45
|
}
|
|
@@ -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,
|
|
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:'
|
|
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
|
-
|
|
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(
|
|
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;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""Public-interface checks for Codex hooks; native tests are opt-in."""
|
|
3
3
|
import argparse
|
|
4
|
+
import hashlib
|
|
4
5
|
import json
|
|
5
6
|
import os
|
|
6
7
|
from pathlib import Path
|
|
@@ -17,6 +18,25 @@ ROOT = Path(__file__).resolve().parents[1]
|
|
|
17
18
|
PLUGIN = ROOT / "plugins/keel"
|
|
18
19
|
CLI = ROOT / "bin/keel.js"
|
|
19
20
|
RECEIVER = PLUGIN / "scripts/codex-mail-hook.js"
|
|
21
|
+
HOOK_LABELS = {
|
|
22
|
+
("SessionStart", "session-start.js"): "Keel: Session context",
|
|
23
|
+
("SessionStart", "codex-mail-hook.js"): "Keel: Mail at session start",
|
|
24
|
+
("UserPromptSubmit", "codex-mail-hook.js"): "Keel: Mail before prompt",
|
|
25
|
+
("PreToolUse", "pretooluse-guard.js"): "Keel: Write guard",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def check_hook_labels(hooks):
|
|
30
|
+
event_names = {name[0].lower(): name[0] for name in HOOK_LABELS}
|
|
31
|
+
found = {
|
|
32
|
+
key: hook.get("statusMessage")
|
|
33
|
+
for hook in hooks
|
|
34
|
+
for key in HOOK_LABELS
|
|
35
|
+
if event_names.get(hook.get("eventName", "").lower()) == key[0]
|
|
36
|
+
and key[1] in hook["command"]
|
|
37
|
+
}
|
|
38
|
+
assert found == HOOK_LABELS, f"Keel hook labels missing or ambiguous: {found}"
|
|
39
|
+
|
|
20
40
|
|
|
21
41
|
|
|
22
42
|
def run(args, cwd=ROOT, env=None, input=None, check=True, timeout=30):
|
|
@@ -48,13 +68,79 @@ def invoke(repo, event, provider=None, timeout_ms=None):
|
|
|
48
68
|
return json.loads(result.stdout) if result.stdout.strip() else None
|
|
49
69
|
|
|
50
70
|
|
|
71
|
+
def read_hook_response(script, repo, event, env=None):
|
|
72
|
+
proc = subprocess.Popen(
|
|
73
|
+
["node", str(PLUGIN / "scripts" / script)],
|
|
74
|
+
cwd=repo, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
75
|
+
stderr=subprocess.PIPE, text=True,
|
|
76
|
+
)
|
|
77
|
+
try:
|
|
78
|
+
proc.stdin.write(json.dumps({"cwd": str(repo), **event}))
|
|
79
|
+
proc.stdin.close()
|
|
80
|
+
proc.stdin = None
|
|
81
|
+
# Exercise the real pipe. A reader that has not been scheduled must
|
|
82
|
+
# still receive the whole JSON response when it starts draining.
|
|
83
|
+
time.sleep(0.3)
|
|
84
|
+
out, err = proc.communicate(timeout=12)
|
|
85
|
+
assert proc.returncode == 0 and not err, (proc.returncode, err)
|
|
86
|
+
try:
|
|
87
|
+
return json.loads(out)["hookSpecificOutput"]
|
|
88
|
+
except (ValueError, KeyError) as error:
|
|
89
|
+
raise AssertionError(f"{script}: hook response truncated ({len(out)} characters)") from error
|
|
90
|
+
finally:
|
|
91
|
+
if proc.poll() is None:
|
|
92
|
+
proc.kill()
|
|
93
|
+
proc.wait(timeout=5)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def buffered_output():
|
|
97
|
+
with tempfile.TemporaryDirectory(prefix="keel-codex-hook-output-") as raw:
|
|
98
|
+
repo = Path(raw)
|
|
99
|
+
change = repo / "openspec/changes/probe"
|
|
100
|
+
change.mkdir(parents=True)
|
|
101
|
+
context = {
|
|
102
|
+
"status": "ready",
|
|
103
|
+
"selection": {"change": "probe", "task": "1.1", "source": "fixture"},
|
|
104
|
+
"read": ["fixture/" + "a" * 180000 + "/projection-tail"],
|
|
105
|
+
}
|
|
106
|
+
provider = repo / "cli.js"
|
|
107
|
+
provider.write_text(
|
|
108
|
+
"process.stdout.write(process.argv[2] === '--version' ? '5.231.5' : "
|
|
109
|
+
+ json.dumps(json.dumps(context)) + ")",
|
|
110
|
+
encoding="utf-8",
|
|
111
|
+
)
|
|
112
|
+
env = dict(os.environ, KEEL_CLI=shlex.join(["node", str(provider)]))
|
|
113
|
+
projection = read_hook_response("session-start.js", repo, {"hook_event_name": "SessionStart"}, env)
|
|
114
|
+
assert "/projection-tail" in projection["additionalContext"]
|
|
115
|
+
tasks = change / "tasks.md"
|
|
116
|
+
tasks.write_text("- [ ] 1.1 Write in Touch only\n", encoding="utf-8")
|
|
117
|
+
touch = [f"src/fixture-{index:05d}.js" for index in range(12000)]
|
|
118
|
+
manifest = {
|
|
119
|
+
"schema": "keel-write-guard/v1", "change": "probe", "task": "1.1",
|
|
120
|
+
"authority": [{"path": str(tasks.relative_to(repo)), "sha256": hashlib.sha256(tasks.read_bytes()).hexdigest()}],
|
|
121
|
+
"touch": touch,
|
|
122
|
+
}
|
|
123
|
+
(repo / "keel").mkdir()
|
|
124
|
+
(repo / "keel/guard.json").write_text(json.dumps(manifest), encoding="utf-8")
|
|
125
|
+
decision = read_hook_response("pretooluse-guard.js", repo, {
|
|
126
|
+
"hook_event_name": "PreToolUse", "tool_name": "Edit",
|
|
127
|
+
"tool_input": {"file_path": str(repo / "src/outside.js")},
|
|
128
|
+
})
|
|
129
|
+
assert decision["permissionDecision"] == "deny"
|
|
130
|
+
assert touch[-1] in decision["permissionDecisionReason"]
|
|
131
|
+
print("codex hook output: complete SessionStart projection and PreToolUse verdict")
|
|
132
|
+
|
|
133
|
+
|
|
51
134
|
def behavior():
|
|
52
135
|
manifest = json.loads((PLUGIN / ".codex-plugin/plugin.json").read_text())
|
|
53
136
|
assert manifest.get("hooks") == "./hooks/codex.json", "Codex still uses the args-only shared hooks"
|
|
54
137
|
hooks = json.loads((PLUGIN / "hooks/codex.json").read_text())["hooks"]
|
|
55
138
|
assert set(hooks) == {"SessionStart", "PreToolUse", "UserPromptSubmit"}
|
|
56
139
|
assert not any(field in json.dumps(hooks) for field in ["asyncRewake", "watchPaths", "FileChanged"])
|
|
57
|
-
|
|
140
|
+
declared = [dict(h, eventName=event) for event, groups in hooks.items() for g in groups for h in g["hooks"]]
|
|
141
|
+
check_hook_labels(declared)
|
|
142
|
+
buffered_output()
|
|
143
|
+
commands = [h["command"] for h in declared]
|
|
58
144
|
for script in ["session-start.js", "pretooluse-guard.js", "codex-mail-hook.js"]:
|
|
59
145
|
assert any(script in command for command in commands), script
|
|
60
146
|
with tempfile.TemporaryDirectory(prefix="keel-codex-mail-") as raw:
|
|
@@ -177,6 +263,7 @@ trust_level = "trusted"
|
|
|
177
263
|
assert not found["errors"], found
|
|
178
264
|
hooks = found["hooks"]
|
|
179
265
|
assert len(hooks) == 4, hooks
|
|
266
|
+
check_hook_labels(hooks)
|
|
180
267
|
assert all(h["trustStatus"] == "untrusted" for h in hooks), hooks
|
|
181
268
|
assert all(".js" in h["command"] for h in hooks), hooks
|
|
182
269
|
assert {h["eventName"] for h in hooks} == {"preToolUse", "sessionStart", "userPromptSubmit"}
|
|
@@ -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.
|
|
38
|
+
PACKAGE_VERSION = "5.231.7"
|
|
39
39
|
|
|
40
40
|
|
|
41
|
-
PROTOCOL_VERSION = "5.231.
|
|
41
|
+
PROTOCOL_VERSION = "5.231.7"
|
|
42
42
|
|
|
43
43
|
|
|
44
44
|
LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
|
package/src/core/branches.js
CHANGED
|
@@ -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
|
|
84
|
-
return new Set(
|
|
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
|
package/src/core/chat/cli.js
CHANGED
|
@@ -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"));
|
package/src/core/codex-host.js
CHANGED
|
@@ -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 ?
|
|
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]
|
|
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};
|
package/src/core/worktrees.js
CHANGED
|
@@ -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 };
|