@christang/keel 5.228.0 → 5.229.1
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/README.md +40 -7
- package/README.zh-CN.md +36 -4
- package/assets/bootstrap/AGENTS.md +1 -1
- package/bin/keel.js +43 -0
- package/npm-shrinkwrap.json +5 -5
- 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 +1 -1
- package/plugins/keel/scripts/pretooluse-guard.js +77 -2
- package/plugins/keel/scripts/session-start.js +7 -0
- package/scripts/bump_version.js +2 -0
- package/scripts/test_codex_host.js +120 -0
- package/scripts/validation/baseline.py +3 -0
- package/scripts/validation/codexhost.py +13 -0
- package/scripts/validation/common.py +2 -2
- package/scripts/validation/docs.py +1 -1
- package/scripts/validation/guard.py +34 -0
- package/scripts/validation/registry.py +29 -0
- package/scripts/validation/sync.py +1608 -0
- package/src/core/capabilities.js +10 -0
- package/src/core/chat/archive.js +6 -2
- package/src/core/chat/notice.js +6 -1
- package/src/core/codex-host.js +298 -0
- package/src/core/config.js +39 -0
- package/src/core/context.js +62 -0
- package/src/core/gates.js +13 -0
- package/src/core/lock.js +514 -8
- package/src/core/patrol.js +1 -0
- package/src/core/shift.js +184 -11
- package/src/core/sync.js +374 -0
- package/src/core/tick.js +7 -1
- package/src/core/worktrees.js +8 -3
package/src/core/capabilities.js
CHANGED
|
@@ -145,6 +145,11 @@ function probeCapabilities(repo, target) {
|
|
|
145
145
|
schemaVersion: 1,
|
|
146
146
|
target,
|
|
147
147
|
capabilities,
|
|
148
|
+
...(target === "codex" ? {host: {managedRoles: {
|
|
149
|
+
level: "manual",
|
|
150
|
+
evidence: "Managed role commands require an explicit verified endpoint and recorded worktree/thread ownership; source tests and dated real-host evidence do not establish this installation's connectivity or trust.",
|
|
151
|
+
command: "keel codex status|start|deliver|handover|drain --repo <path> --json",
|
|
152
|
+
}}} : {}),
|
|
148
153
|
guard: guardDiagnostics(repo, target),
|
|
149
154
|
compaction: compactionDiagnostics(target),
|
|
150
155
|
warnings: [
|
|
@@ -247,6 +252,11 @@ function renderCapabilities(result) {
|
|
|
247
252
|
+ `command: ${capability.command}`
|
|
248
253
|
);
|
|
249
254
|
}
|
|
255
|
+
if (result.host) {
|
|
256
|
+
for (const [dimension, entry] of Object.entries(result.host)) {
|
|
257
|
+
lines.push(`host ${dimension}: ${entry.level} - ${entry.evidence}; command: ${entry.command}`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
250
260
|
if (result.guard) {
|
|
251
261
|
for (const [dimension, entry] of Object.entries(result.guard)) {
|
|
252
262
|
lines.push(`guard ${dimension}: ${entry.level} - ${entry.evidence}`);
|
package/src/core/chat/archive.js
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
// 90 days and deletes after a year; the project's own repository keeps
|
|
5
5
|
// everything, on an orphan branch `keel-chat` that never meets `main`.
|
|
6
6
|
//
|
|
7
|
-
// Only the synced layer is archived — records, cursors, aliases, presence
|
|
7
|
+
// Only the synced layer is archived — records, cursors, aliases, presence,
|
|
8
|
+
// hand-over notes —
|
|
8
9
|
// the files that are written by one writer and never rewritten in place, so
|
|
9
10
|
// two machines' archives merge by the union of their paths. The commit is
|
|
10
11
|
// made with plumbing and a temporary index: the worktree, the real index, and
|
|
@@ -23,7 +24,10 @@ const { loadChatConfig } = require("./config");
|
|
|
23
24
|
|
|
24
25
|
const { ChatError } = store;
|
|
25
26
|
const BRANCH = "refs/heads/keel-chat";
|
|
26
|
-
|
|
27
|
+
// `shift-notes/` holds hand-over notes, each written once under a new name
|
|
28
|
+
// (#526 D9), so it merges by the union of paths like the rest; the rewritten
|
|
29
|
+
// `shift/<role>.md` stays out.
|
|
30
|
+
const SYNCED_ROOTS = ["groups", "cursors", "members", "presence", "shift-notes"];
|
|
27
31
|
|
|
28
32
|
function git(where, args, { env = {}, input = null, allowFail = false } = {}) {
|
|
29
33
|
const result = spawnSync("git", args, {
|
package/src/core/chat/notice.js
CHANGED
|
@@ -458,7 +458,7 @@ function segmentsFile(where, role) {
|
|
|
458
458
|
}
|
|
459
459
|
|
|
460
460
|
// Where Keel keeps a copy of a role's ended transcript (#343). It stays on this
|
|
461
|
-
// machine: the chat archive syncs none of `shift/`.
|
|
461
|
+
// machine: the chat archive syncs `shift-notes/` and none of `shift/`.
|
|
462
462
|
function keptFile(where, role, transcript) {
|
|
463
463
|
return path.join(where.root, "shift", "transcripts", role, `${path.basename(transcript)}.gz`);
|
|
464
464
|
}
|
|
@@ -744,6 +744,11 @@ function hook(event, input, { mail = false } = {}) {
|
|
|
744
744
|
// The owner's language is restated on every prompt, role or not (#305 D4).
|
|
745
745
|
let languageLine = null;
|
|
746
746
|
if (where && event === "user-prompt-submit") {
|
|
747
|
+
try {
|
|
748
|
+
require("../lock").renewHeld(where, { prompt: true });
|
|
749
|
+
} catch {
|
|
750
|
+
// Prompt-time renewal never blocks or reports a network failure.
|
|
751
|
+
}
|
|
747
752
|
try {
|
|
748
753
|
const { readOwnerLanguage, ownerLanguageRule } = require("../config");
|
|
749
754
|
const language = readOwnerLanguage(where.worktree);
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const http = require('node:http');
|
|
3
|
+
const crypto = require('node:crypto');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const os = require('node:os');
|
|
6
|
+
const MAX_MESSAGE = 16 * 1024 * 1024;
|
|
7
|
+
|
|
8
|
+
// The managed daemon speaks WebSocket over a Unix socket, not JSON lines.
|
|
9
|
+
function connect(socketPath, timeout = 5000) {
|
|
10
|
+
return new Promise((resolve, reject) => {
|
|
11
|
+
const key = crypto.randomBytes(16).toString('base64');
|
|
12
|
+
const pending = new Map();
|
|
13
|
+
let socket, opened = false, closed = false, sequence = 0;
|
|
14
|
+
let buffer = Buffer.alloc(0), fragments = [], fragmentSize = 0;
|
|
15
|
+
const request = http.request({socketPath, path: '/', headers: {
|
|
16
|
+
Host: 'localhost', Upgrade: 'websocket', Connection: 'Upgrade',
|
|
17
|
+
'Sec-WebSocket-Key': key, 'Sec-WebSocket-Version': '13',
|
|
18
|
+
}});
|
|
19
|
+
const deadline = setTimeout(() => fail(Error('Codex host connection timeout')), timeout);
|
|
20
|
+
function fail(error) {
|
|
21
|
+
if (closed) return;
|
|
22
|
+
closed = true;
|
|
23
|
+
clearTimeout(deadline);
|
|
24
|
+
for (const entry of pending.values()) {
|
|
25
|
+
clearTimeout(entry.timer);
|
|
26
|
+
entry.reject(error);
|
|
27
|
+
}
|
|
28
|
+
pending.clear();
|
|
29
|
+
if (!opened) reject(error);
|
|
30
|
+
request.destroy();
|
|
31
|
+
if (socket) socket.destroy();
|
|
32
|
+
}
|
|
33
|
+
function send(opcode, body) {
|
|
34
|
+
if (closed) throw Error('Codex host disconnected');
|
|
35
|
+
if (body.length > MAX_MESSAGE) throw Error('Codex request too large');
|
|
36
|
+
const mask = crypto.randomBytes(4);
|
|
37
|
+
const header = Buffer.alloc(body.length < 126 ? 2 : body.length <= 65535 ? 4 : 10);
|
|
38
|
+
header[0] = 128 | opcode;
|
|
39
|
+
if (header.length === 2) header[1] = 128 | body.length;
|
|
40
|
+
else if (header.length === 4) {header[1] = 254; header.writeUInt16BE(body.length, 2);}
|
|
41
|
+
else {header[1] = 255; header.writeBigUInt64BE(BigInt(body.length), 2);}
|
|
42
|
+
const payload = Buffer.from(body);
|
|
43
|
+
for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i % 4];
|
|
44
|
+
socket.write(Buffer.concat([header, mask, payload]));
|
|
45
|
+
}
|
|
46
|
+
function message(body) {
|
|
47
|
+
const value = JSON.parse(body.toString('utf8'));
|
|
48
|
+
if (typeof value.method === 'string') return;
|
|
49
|
+
const entry = pending.get(value.id);
|
|
50
|
+
if (!entry) return; // Notifications are not acknowledgements of pending RPCs.
|
|
51
|
+
pending.delete(value.id);
|
|
52
|
+
clearTimeout(entry.timer);
|
|
53
|
+
if (value.error) entry.reject(Error(value.error.message));
|
|
54
|
+
else entry.resolve(value.result);
|
|
55
|
+
}
|
|
56
|
+
function receive(chunk) {
|
|
57
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
58
|
+
try {
|
|
59
|
+
while (buffer.length >= 2) {
|
|
60
|
+
const fin = Boolean(buffer[0] & 128), opcode = buffer[0] & 15;
|
|
61
|
+
if ((buffer[0] & 112) || (buffer[1] & 128)) throw Error('Invalid Codex WebSocket frame');
|
|
62
|
+
let length = buffer[1] & 127, offset = 2;
|
|
63
|
+
if (length === 126) {
|
|
64
|
+
if (buffer.length < 4) return;
|
|
65
|
+
length = buffer.readUInt16BE(2); offset = 4;
|
|
66
|
+
} else if (length === 127) {
|
|
67
|
+
if (buffer.length < 10) return;
|
|
68
|
+
const large = buffer.readBigUInt64BE(2);
|
|
69
|
+
if (large > BigInt(MAX_MESSAGE)) throw Error('Codex response too large');
|
|
70
|
+
length = Number(large); offset = 10;
|
|
71
|
+
}
|
|
72
|
+
if (length > MAX_MESSAGE || fragmentSize + length > MAX_MESSAGE) throw Error('Codex response too large');
|
|
73
|
+
if (opcode >= 8 && (!fin || length > 125)) throw Error('Invalid Codex control frame');
|
|
74
|
+
if (buffer.length < offset + length) return;
|
|
75
|
+
const body = buffer.subarray(offset, offset + length);
|
|
76
|
+
buffer = buffer.subarray(offset + length);
|
|
77
|
+
if (opcode === 8) throw Error('Codex host closed connection');
|
|
78
|
+
if (opcode === 9) {send(10, body); continue;}
|
|
79
|
+
if (opcode === 10) continue;
|
|
80
|
+
if (opcode === 1 && !fragments.length) {
|
|
81
|
+
if (fin) message(body);
|
|
82
|
+
else {fragments = [body]; fragmentSize = length;}
|
|
83
|
+
} else if (opcode === 0 && fragments.length) {
|
|
84
|
+
fragments.push(body); fragmentSize += length;
|
|
85
|
+
if (fin) {message(Buffer.concat(fragments)); fragments = []; fragmentSize = 0;}
|
|
86
|
+
} else throw Error('Unsupported Codex WebSocket frame');
|
|
87
|
+
}
|
|
88
|
+
} catch (error) {fail(error);}
|
|
89
|
+
}
|
|
90
|
+
request.on('error', fail);
|
|
91
|
+
request.on('response', response => {response.resume(); fail(Error(`WebSocket upgrade refused: ${response.statusCode}`));});
|
|
92
|
+
request.on('upgrade', (response, peer, head) => {
|
|
93
|
+
socket = peer;
|
|
94
|
+
const expected = crypto.createHash('sha1').update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64');
|
|
95
|
+
if (response.headers['sec-websocket-accept'] !== expected) return fail(Error('Invalid WebSocket handshake'));
|
|
96
|
+
clearTimeout(deadline);
|
|
97
|
+
socket.on('data', receive);
|
|
98
|
+
socket.on('error', fail);
|
|
99
|
+
socket.on('close', () => fail(Error('Codex host disconnected')));
|
|
100
|
+
opened = true;
|
|
101
|
+
resolve({
|
|
102
|
+
call(method, params, callTimeout = timeout) {
|
|
103
|
+
return new Promise((resolveCall, rejectCall) => {
|
|
104
|
+
if (closed) return rejectCall(Error('Codex host disconnected'));
|
|
105
|
+
const id = ++sequence;
|
|
106
|
+
const timer = setTimeout(() => fail(Error(`Codex ${method} timeout`)), callTimeout);
|
|
107
|
+
pending.set(id, {resolve: resolveCall, reject: rejectCall, timer});
|
|
108
|
+
try {send(1, Buffer.from(JSON.stringify({id, method, params})));}
|
|
109
|
+
catch (error) {fail(error);}
|
|
110
|
+
});
|
|
111
|
+
},
|
|
112
|
+
notify(method, params = {}) {send(1, Buffer.from(JSON.stringify({method, params})));},
|
|
113
|
+
close() {fail(Error('Codex host disconnected'));},
|
|
114
|
+
});
|
|
115
|
+
if (head.length) receive(head);
|
|
116
|
+
});
|
|
117
|
+
request.end();
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function run(args) {
|
|
122
|
+
let client;
|
|
123
|
+
let reservation;
|
|
124
|
+
let roleLock;
|
|
125
|
+
try {
|
|
126
|
+
const action = args.shift();
|
|
127
|
+
if (!["status", "start", "deliver", "handover", "drain"].includes(action)) throw Error("Usage: keel codex status|start|deliver|handover|drain [--socket path] [--role name] [--repo path] [--thread id] [--timeout ms] [--json]");
|
|
128
|
+
const options = {socket: path.join(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"), "app-server-control/app-server-control.sock"), timeout: 5000, repo: process.cwd()};
|
|
129
|
+
let explicitSocket = false;
|
|
130
|
+
let explicitTimeout = false;
|
|
131
|
+
while (args.length) {
|
|
132
|
+
const flag = args.shift();
|
|
133
|
+
if (flag === "--json") options.json = true;
|
|
134
|
+
else if (["--socket", "--thread", "--timeout", "--role", "--repo", "--record", "--text", "--note"].includes(flag)) {
|
|
135
|
+
const value = args.shift();
|
|
136
|
+
if (!value || value.startsWith("--")) throw Error(`${flag} needs a value`);
|
|
137
|
+
options[flag.slice(2)] = value;
|
|
138
|
+
if (flag === "--socket") explicitSocket = true;
|
|
139
|
+
if (flag === "--timeout") explicitTimeout = true;
|
|
140
|
+
} else throw Error(`Unknown argument ${flag}`);
|
|
141
|
+
}
|
|
142
|
+
const ms = Number(options.timeout);
|
|
143
|
+
if (!Number.isInteger(ms) || ms < 50 || ms > 60000) throw Error("timeout must be 50–60000 milliseconds");
|
|
144
|
+
const fs = require("node:fs");
|
|
145
|
+
const store = require("./chat/store");
|
|
146
|
+
if (action === "drain") {
|
|
147
|
+
const deliveries = wakeManaged(store.requireLocation(path.resolve(options.repo)), options.role);
|
|
148
|
+
process.stdout.write(JSON.stringify({deliveries}) + "\n");
|
|
149
|
+
return deliveries.some(entry => entry.error) ? 1 : 0;
|
|
150
|
+
}
|
|
151
|
+
let where, file, recorded;
|
|
152
|
+
if (options.role) {
|
|
153
|
+
store.checkName(options.role, "Role");
|
|
154
|
+
where = store.requireLocation(path.resolve(options.repo));
|
|
155
|
+
if (action === "start" && options.role === "keel") throw Error("Role name keel is reserved");
|
|
156
|
+
if (action === "start" && store.canonicalRole(where.root, options.role) !== options.role) throw Error("Role was renamed; bind its current name before starting a managed thread");
|
|
157
|
+
file = path.join(where.root, "codex-roles", `${options.role}.json`);
|
|
158
|
+
if (fs.existsSync(file)) recorded = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
159
|
+
if (action === "start" && store.currentRole(where) && store.currentRole(where) !== options.role) throw Error("worktree already belongs to a different role");
|
|
160
|
+
if (action === "start" && recorded) throw Error(`managed role ${options.role} already exists; no new thread started`);
|
|
161
|
+
if (action !== "start") {
|
|
162
|
+
if (!recorded || recorded.state !== "managed") throw Error("managed role not found or creation outcome unknown");
|
|
163
|
+
if (recorded.worktree !== where.worktree) throw Error("managed role worktree mismatch");
|
|
164
|
+
if (explicitSocket && options.socket !== recorded.socket) throw Error("managed role endpoint mismatch");
|
|
165
|
+
options.socket = recorded.socket;
|
|
166
|
+
options.thread = recorded.thread;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (action === "start" && !options.role) throw Error("start needs --role");
|
|
170
|
+
if (["deliver", "handover"].includes(action)) {
|
|
171
|
+
if (!recorded) throw Error("operation needs a managed --role");
|
|
172
|
+
const candidateLock = `${file}.lock`;
|
|
173
|
+
const fd = fs.openSync(candidateLock, "wx"); fs.closeSync(fd);
|
|
174
|
+
roleLock = candidateLock;
|
|
175
|
+
// A contender may have read before another process finished its claim.
|
|
176
|
+
// The durable decision must be read under the lock this call now owns.
|
|
177
|
+
recorded = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
178
|
+
if (recorded.state !== "managed" || recorded.role !== options.role || recorded.worktree !== where.worktree || recorded.socket !== options.socket) throw Error("managed role identity changed before operation lock");
|
|
179
|
+
if (action === "deliver" && (!options.record || !options.text)) throw Error("deliver needs --record and --text");
|
|
180
|
+
if (action === "handover" && !options.note) throw Error("handover needs --note");
|
|
181
|
+
}
|
|
182
|
+
client = await connect(options.socket, ms);
|
|
183
|
+
const host = await client.call("initialize", {clientInfo: {name: "keel", version: "1"}});
|
|
184
|
+
if (!host || typeof host.userAgent !== "string" || !host.userAgent) throw Error("Codex host returned no initialization identity");
|
|
185
|
+
client.notify("initialized");
|
|
186
|
+
const result = {socket: options.socket, host};
|
|
187
|
+
if (action === "start") {
|
|
188
|
+
fs.mkdirSync(path.dirname(file), {recursive: true});
|
|
189
|
+
const fd = fs.openSync(file, "wx");
|
|
190
|
+
fs.writeFileSync(fd, JSON.stringify({state: "creation-pending", role: options.role, worktree: where.worktree, socket: options.socket}));
|
|
191
|
+
fs.closeSync(fd);
|
|
192
|
+
reservation = file;
|
|
193
|
+
const started = await client.call("thread/start", {cwd: where.worktree, sandbox: "workspace-write", approvalPolicy: "on-request", serviceName: "keel"});
|
|
194
|
+
const thread = started.thread;
|
|
195
|
+
if (!thread || !thread.id || thread.cwd !== where.worktree) throw Error("Codex created thread with unexpected identity");
|
|
196
|
+
const entry = {state: "managed", role: options.role, thread: thread.id, worktree: where.worktree, socket: options.socket};
|
|
197
|
+
store.writeJsonAtomic(where, file, entry);
|
|
198
|
+
store.setRole(where, options.role);
|
|
199
|
+
Object.assign(result, entry);
|
|
200
|
+
} else if (["deliver", "handover"].includes(action)) {
|
|
201
|
+
let thread = (await client.call("thread/read", {threadId: recorded.thread, includeTurns: false})).thread;
|
|
202
|
+
const owned = value => value && value.id === recorded.thread && value.cwd === recorded.worktree;
|
|
203
|
+
if (!owned(thread)) throw Error("managed role identity mismatch");
|
|
204
|
+
const claims = recorded.deliveries || {};
|
|
205
|
+
const key = options.record ? crypto.createHash("sha256").update(options.record).digest("hex") : null;
|
|
206
|
+
if (action === "deliver" && claims[key]) {
|
|
207
|
+
// Deduplication is a recorded outcome, not a reason to load a thread.
|
|
208
|
+
if (claims[key].state !== "delivered" || typeof claims[key].turn !== "string" || !claims[key].turn) {
|
|
209
|
+
throw Error("delivery outcome unknown; claim retained, no retry started");
|
|
210
|
+
}
|
|
211
|
+
Object.assign(result, {state: "already-delivered", turn: claims[key].turn});
|
|
212
|
+
} else {
|
|
213
|
+
if (action === "deliver" && thread.status && thread.status.type === "notLoaded") {
|
|
214
|
+
// Only this recorded owned identity may be loaded. Keep this same
|
|
215
|
+
// connection alive through the subsequent turn/start and preserve
|
|
216
|
+
// the thread's saved permissions rather than overriding them.
|
|
217
|
+
thread = (await client.call("thread/resume", {threadId: recorded.thread, serviceName: "keel"}, explicitTimeout ? ms : Math.max(ms, 15000))).thread;
|
|
218
|
+
if (!owned(thread)) throw Error("resumed managed role identity mismatch");
|
|
219
|
+
}
|
|
220
|
+
if (!thread.status || !["idle", "active"].includes(thread.status.type)) {
|
|
221
|
+
throw Error("managed role state is not verified idle or active; no work started");
|
|
222
|
+
}
|
|
223
|
+
if (thread.status.type === "active") {
|
|
224
|
+
Object.assign(result, {state: "waiting", thread: recorded.thread});
|
|
225
|
+
} else if (action === "deliver") {
|
|
226
|
+
claims[key] = {record: options.record, state: "pending"};
|
|
227
|
+
recorded.deliveries = claims;
|
|
228
|
+
store.writeJsonAtomic(where, file, recorded);
|
|
229
|
+
const turn = (await client.call("turn/start", {threadId: recorded.thread, input: [{type: "text", text: (recorded.note ? `Handover note (context only):\n${recorded.note}\n\n` : "") + options.text}]})).turn;
|
|
230
|
+
if (!turn || !turn.id) throw Error("Codex returned no turn identity; claim retained");
|
|
231
|
+
claims[key] = {record: options.record, state: "delivered", turn: turn.id};
|
|
232
|
+
store.writeJsonAtomic(where, file, recorded);
|
|
233
|
+
Object.assign(result, {state: "delivered", turn: turn.id});
|
|
234
|
+
} else {
|
|
235
|
+
if (recorded.handover) throw Error("handover outcome unknown; no successor started");
|
|
236
|
+
recorded.handover = {state: "pending", note: options.note};
|
|
237
|
+
store.writeJsonAtomic(where, file, recorded);
|
|
238
|
+
const next = (await client.call("thread/start", {cwd: recorded.worktree, sandbox: "workspace-write", approvalPolicy: "on-request", serviceName: "keel"})).thread;
|
|
239
|
+
if (!next || !next.id || next.cwd !== recorded.worktree) throw Error("successor identity mismatch; handover retained");
|
|
240
|
+
const history = [...(recorded.history || []), {thread: recorded.thread, note: options.note}];
|
|
241
|
+
delete recorded.handover;
|
|
242
|
+
Object.assign(recorded, {thread: next.id, history, note: options.note});
|
|
243
|
+
store.writeJsonAtomic(where, file, recorded);
|
|
244
|
+
Object.assign(result, {state: "handed-over", thread: next.id, note: options.note});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
} else if (options.thread) {
|
|
248
|
+
result.thread = (await client.call("thread/read", {threadId: options.thread, includeTurns: false})).thread;
|
|
249
|
+
if (recorded && (result.thread.id !== recorded.thread || result.thread.cwd !== recorded.worktree)) throw Error("managed role identity mismatch");
|
|
250
|
+
}
|
|
251
|
+
process.stdout.write((options.json ? JSON.stringify(result) : `Codex host connected: ${host.userAgent}${result.role ? `; role ${result.role}: ${result.thread}` : ""}`) + "\n");
|
|
252
|
+
return 0;
|
|
253
|
+
} catch (error) {
|
|
254
|
+
process.stderr.write(`keel codex: ${error.message}${reservation ? "; creation record retained to prevent duplicate start" : ""}\n`);
|
|
255
|
+
return 1;
|
|
256
|
+
} finally {
|
|
257
|
+
if (client) client.close();
|
|
258
|
+
if (roleLock) require("node:fs").rmSync(roleLock, {force: true});
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// Use the existing mailbox addressing rules and parking decisions. Calling the
|
|
262
|
+
// public CLI in a child keeps synchronous tick callers and Claude behavior intact.
|
|
263
|
+
function wakeManaged(where, onlyRole = null) {
|
|
264
|
+
const fs = require('node:fs');
|
|
265
|
+
const store = require('./chat/store');
|
|
266
|
+
const directory = path.join(where.root, 'codex-roles');
|
|
267
|
+
if (!fs.existsSync(directory)) return [];
|
|
268
|
+
const results = [];
|
|
269
|
+
for (const name of fs.readdirSync(directory).filter(name => name.endsWith('.json')).sort()) {
|
|
270
|
+
let entry;
|
|
271
|
+
try {entry = JSON.parse(fs.readFileSync(path.join(directory, name), 'utf8'));}
|
|
272
|
+
catch (error) {results.push({role: name, error: error.message}); continue;}
|
|
273
|
+
const role = name.slice(0, -5);
|
|
274
|
+
if (onlyRole && onlyRole !== role) continue;
|
|
275
|
+
if (entry.state !== 'managed' || entry.role !== role) {
|
|
276
|
+
results.push({role, error: 'managed role identity or creation outcome unverified'}); continue;
|
|
277
|
+
}
|
|
278
|
+
if (require('./chat/notice').parkOf(where, role)) continue;
|
|
279
|
+
const bound = store.readJsonFile(path.join(where.root, 'roles.json'));
|
|
280
|
+
if (bound[entry.worktree] !== role) {
|
|
281
|
+
results.push({role, error: 'managed worktree role binding mismatch'}); continue;
|
|
282
|
+
}
|
|
283
|
+
for (const record of store.unread(where, role).filter(record => store.wakes(record, role))) {
|
|
284
|
+
const prompt = `${store.DATA_NOTICE}\nRun keel context before acting.\nAddressed record ${record.id} from ${record.from}:\n${record.text || record.body || ''}`;
|
|
285
|
+
const child = require('node:child_process').spawnSync(process.execPath, [
|
|
286
|
+
path.resolve(__dirname, '../../bin/keel.js'), 'codex', 'deliver',
|
|
287
|
+
'--repo', entry.worktree, '--role', role, '--record', record.id, '--text', prompt, '--json',
|
|
288
|
+
], {encoding: 'utf8', timeout: 40000});
|
|
289
|
+
let result;
|
|
290
|
+
try {result = JSON.parse(child.stdout);} catch {result = {};}
|
|
291
|
+
if (child.error || child.status !== 0) result.error = child.error ? child.error.message : child.stderr.trim();
|
|
292
|
+
results.push({role, record: record.id, ...result});
|
|
293
|
+
if (result.error || result.state === 'waiting' || result.state === 'delivered') break;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return results;
|
|
297
|
+
}
|
|
298
|
+
module.exports = {connect, run, wakeManaged};
|
package/src/core/config.js
CHANGED
|
@@ -49,6 +49,11 @@ const STANDING_AUTHORIZATION_ACTIONS = [
|
|
|
49
49
|
// may. It grants no bulk tag push and no tag deletion, and it widens no
|
|
50
50
|
// branch, so a bare `push` beside it is not a mixed declaration.
|
|
51
51
|
"push-tag",
|
|
52
|
+
// Keel's own pushes of branch-lock refs under `refs/keel/lock/` (#526 D10):
|
|
53
|
+
// acquiring, renewing, releasing, taking over and breaking a lock, and
|
|
54
|
+
// nothing else. A work branch Keel pushes still needs `push` or a matching
|
|
55
|
+
// `push:<glob>`. Bare: a lock ref is in this repository's own remote.
|
|
56
|
+
"device-sync",
|
|
52
57
|
];
|
|
53
58
|
|
|
54
59
|
// The actions whose credential reaches further than the checkout the
|
|
@@ -180,6 +185,7 @@ const CONFIG_DECLARATIONS = [
|
|
|
180
185
|
"patrol",
|
|
181
186
|
"shift",
|
|
182
187
|
"branches",
|
|
188
|
+
"sync",
|
|
183
189
|
"owner_language",
|
|
184
190
|
];
|
|
185
191
|
|
|
@@ -1166,6 +1172,38 @@ function readBranchesDeclaration(repo) {
|
|
|
1166
1172
|
return declared;
|
|
1167
1173
|
}
|
|
1168
1174
|
|
|
1175
|
+
// `sync:` (#526 D11): `lock`, a boolean that turns on the branch lock at the
|
|
1176
|
+
// sync points, and `ttl`, the lease length from 5 minutes to 24 hours. A
|
|
1177
|
+
// declaration Keel cannot fully read is named and behaves as absent, the rule
|
|
1178
|
+
// every other declaration here follows.
|
|
1179
|
+
const SYNC_TTL_DEFAULT = "30m";
|
|
1180
|
+
const SYNC_KEYS = ["lock", "ttl"];
|
|
1181
|
+
|
|
1182
|
+
function readSyncDeclaration(repo) {
|
|
1183
|
+
const block = configBlockLines(repo, "sync");
|
|
1184
|
+
if (!block) return { declared: false, lock: false, ttl: SYNC_TTL_DEFAULT, ttlSeconds: 1800, message: null };
|
|
1185
|
+
const absent = (message) => ({ declared: false, lock: false, ttl: SYNC_TTL_DEFAULT, ttlSeconds: 1800, message });
|
|
1186
|
+
if (block.inline) return absent(`keel/config.yaml \`sync:\` is written inline (\`${block.inline}\`); give \`lock:\` and \`ttl:\` as indented entries. It is ignored until then.`);
|
|
1187
|
+
const values = {};
|
|
1188
|
+
for (const line of block.lines) {
|
|
1189
|
+
const entry = line.match(/^\s+(\w+)\s*:\s*(\S+)\s*$/);
|
|
1190
|
+
if (!entry || !SYNC_KEYS.includes(entry[1])) {
|
|
1191
|
+
return absent(`keel/config.yaml \`sync:\` has a line Keel cannot read: \`${line.trim()}\`; it takes only \`lock: true|false\` and \`ttl: <n>m|<n>h\`. The declaration is ignored until it is corrected.`);
|
|
1192
|
+
}
|
|
1193
|
+
values[entry[1]] = entry[2];
|
|
1194
|
+
}
|
|
1195
|
+
if (values.lock !== undefined && !["true", "false"].includes(values.lock)) {
|
|
1196
|
+
return absent(`keel/config.yaml \`sync:\` declares \`lock: ${values.lock}\`, which is not true or false; the declaration is ignored until it is corrected.`);
|
|
1197
|
+
}
|
|
1198
|
+
const ttl = values.ttl === undefined ? SYNC_TTL_DEFAULT : values.ttl;
|
|
1199
|
+
const match = ttl.match(/^(\d+)([mh])$/);
|
|
1200
|
+
const seconds = match ? Number(match[1]) * (match[2] === "h" ? 3600 : 60) : NaN;
|
|
1201
|
+
if (!match || seconds < 300 || seconds > 86400) {
|
|
1202
|
+
return absent(`keel/config.yaml \`sync:\` declares \`ttl: ${ttl}\`; a TTL is <n>m or <n>h from 5 minutes to 24 hours. The declaration is ignored until it is corrected.`);
|
|
1203
|
+
}
|
|
1204
|
+
return { declared: true, lock: values.lock === "true", ttl, ttlSeconds: seconds, message: null };
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1169
1207
|
function durationSeconds(value) {
|
|
1170
1208
|
const match = String(value || "").match(/^(\d+)([smhd])$/);
|
|
1171
1209
|
return match ? Number(match[1]) * { s: 1, m: 60, h: 3600, d: 86400 }[match[2]] : null;
|
|
@@ -1191,6 +1229,7 @@ module.exports = {
|
|
|
1191
1229
|
readPatrolDeclarations,
|
|
1192
1230
|
readShiftDeclaration,
|
|
1193
1231
|
readBranchesDeclaration,
|
|
1232
|
+
readSyncDeclaration,
|
|
1194
1233
|
durationSeconds,
|
|
1195
1234
|
patrolReminder,
|
|
1196
1235
|
readIssueRoles,
|
package/src/core/context.js
CHANGED
|
@@ -19,6 +19,7 @@ const {
|
|
|
19
19
|
readMergeDeclaration,
|
|
20
20
|
readReadOnlyRoles,
|
|
21
21
|
readPatrolDeclaration,
|
|
22
|
+
readSyncDeclaration,
|
|
22
23
|
readOwnerLanguage,
|
|
23
24
|
ownerLanguageRule,
|
|
24
25
|
} = require("./config");
|
|
@@ -786,6 +787,56 @@ function gitWarnings(repo) {
|
|
|
786
787
|
: [];
|
|
787
788
|
}
|
|
788
789
|
|
|
790
|
+
function localOnlyWarning(repo) {
|
|
791
|
+
let found;
|
|
792
|
+
try {
|
|
793
|
+
found = require("./sync").status(repo);
|
|
794
|
+
} catch {
|
|
795
|
+
return null;
|
|
796
|
+
}
|
|
797
|
+
if (!found.hasRemote || !found.localOnly) return null;
|
|
798
|
+
const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
799
|
+
const parts = [];
|
|
800
|
+
if (found.branches.length) parts.push(plural(found.branches.length, "local-only branch", "local-only branches"));
|
|
801
|
+
if (found.worktrees.length) parts.push(plural(found.worktrees.length, "worktree with uncommitted or unpushed work", "worktrees with uncommitted or unpushed work"));
|
|
802
|
+
if (found.stashes.length) parts.push(plural(found.stashes.length, "stash entry", "stash entries"));
|
|
803
|
+
return `Only on this machine (selection-neutral, from local refs): ${parts.join(", ")}; \`keel sync status\` lists them with their fixes.`;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// Under `sync: lock: true` a task waits for this device to hold the branch's
|
|
807
|
+
// lock (#526 D15): the next action becomes taking it, read from the last
|
|
808
|
+
// fetched lock ref, never the network. Status and selection stay.
|
|
809
|
+
function lockNextAction(repo, context) {
|
|
810
|
+
if (!context.nextAction || !["task-start", "task-complete"].includes(context.nextAction.kind)) return;
|
|
811
|
+
const run = (args) => {
|
|
812
|
+
const r = spawnSync("git", args, { cwd: repo, encoding: "utf8", env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" } });
|
|
813
|
+
return r.status === 0 ? String(r.stdout || "").trim() : "";
|
|
814
|
+
};
|
|
815
|
+
const branch = run(["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
816
|
+
if (!branch) return;
|
|
817
|
+
const lockModule = require("./lock");
|
|
818
|
+
const sha = run(["rev-parse", "--verify", "--quiet", `${lockModule.LOCK_PREFIX}${branch}`]);
|
|
819
|
+
const lock = sha ? lockModule.parseLock(repo, sha) : null;
|
|
820
|
+
let device = null;
|
|
821
|
+
try {
|
|
822
|
+
device = lockModule.existingDeviceId(require("./chat/store").locate(repo));
|
|
823
|
+
} catch {
|
|
824
|
+
device = null;
|
|
825
|
+
}
|
|
826
|
+
const now = Date.now();
|
|
827
|
+
if (lock && lock.state === "held" && device && lock.device === device && now <= Date.parse(lock.expires || "")) return;
|
|
828
|
+
const free = lock && (lock.state === "released" || (lock.state === "held" && !lockModule.liveFor(lock, now, lockModule.GRACE_MS)));
|
|
829
|
+
const mine = lock && context.role && lockModule.roleOf(lock.holder) === context.role;
|
|
830
|
+
if (free && mine) {
|
|
831
|
+
context.nextAction = { kind: "shift-resume", command: "keel shift resume" };
|
|
832
|
+
} else {
|
|
833
|
+
context.nextAction = { kind: "lock-acquire", command: `keel lock acquire --branch ${branch}` };
|
|
834
|
+
}
|
|
835
|
+
context.reasons.push(lock
|
|
836
|
+
? `The branch lock of ${branch}, as last fetched, is ${lock.state} by ${lock.holder} (expires ${lock.expires || "unknown"}), not held by this device; sync: lock: true needs it before a task.`
|
|
837
|
+
: `Branch ${branch} has no lock as last fetched; sync: lock: true needs this device to hold it before a task.`);
|
|
838
|
+
}
|
|
839
|
+
|
|
789
840
|
// A session whose bound chat role is listed in `read_only_roles:` owns no
|
|
790
841
|
// change, so it gets one idle line instead of candidates (#246 D4).
|
|
791
842
|
function readOnlyContext(repo, readOnly) {
|
|
@@ -896,7 +947,18 @@ function resolveContext(repo, options) {
|
|
|
896
947
|
}
|
|
897
948
|
}
|
|
898
949
|
}
|
|
950
|
+
// `sync:` (#526 D11): reported when in force, named when unreadable.
|
|
951
|
+
const syncDeclaration = readSyncDeclaration(repo);
|
|
952
|
+
if (syncDeclaration.message) context.warnings.push(syncDeclaration.message);
|
|
953
|
+
if (syncDeclaration.declared) {
|
|
954
|
+
context.sync = { lock: syncDeclaration.lock, ttl: syncDeclaration.ttl, ttlSeconds: syncDeclaration.ttlSeconds };
|
|
955
|
+
}
|
|
899
956
|
context.warnings.push(...gitWarnings(repo));
|
|
957
|
+
// What exists only on this machine (#526 D15): one offline line, which never
|
|
958
|
+
// changes status, selection or the next action.
|
|
959
|
+
const localOnly = localOnlyWarning(repo);
|
|
960
|
+
if (localOnly) context.warnings.push(localOnly);
|
|
961
|
+
if (syncDeclaration.lock) lockNextAction(repo, context);
|
|
900
962
|
// A broken `authorize:` declaration is otherwise reported only by
|
|
901
963
|
// `keel --doctor`, an explicitly-invoked diagnostic — surfaced here too so a
|
|
902
964
|
// session that runs `keel context` first (per `AGENTS.md`) learns the
|
package/src/core/gates.js
CHANGED
|
@@ -557,6 +557,11 @@ function fillRecordSlots(repo, options) {
|
|
|
557
557
|
};
|
|
558
558
|
}
|
|
559
559
|
|
|
560
|
+
function syncGateCheck(repo, stage) {
|
|
561
|
+
if (!require("./config").readSyncDeclaration(repo).lock) return { problems: [], warnings: [] };
|
|
562
|
+
return require("./lock").gateSyncCheck(repo, stage);
|
|
563
|
+
}
|
|
564
|
+
|
|
560
565
|
function taskStart(repo, options) {
|
|
561
566
|
if (!options.record) return taskStartChecked(repo, options);
|
|
562
567
|
const filled = fillRecordSlots(repo, options);
|
|
@@ -636,6 +641,10 @@ function taskStartChecked(repo, options) {
|
|
|
636
641
|
);
|
|
637
642
|
}
|
|
638
643
|
}
|
|
644
|
+
// The branch lock at a sync point (#526 D12): read only, and only when the
|
|
645
|
+
// repository declares it.
|
|
646
|
+
const syncCheck = syncGateCheck(repo, "task-start");
|
|
647
|
+
problems.push(...syncCheck.problems);
|
|
639
648
|
const result = gateResult(
|
|
640
649
|
"task-start",
|
|
641
650
|
problems.length > 0 ? "fail" : "pass",
|
|
@@ -645,6 +654,7 @@ function taskStartChecked(repo, options) {
|
|
|
645
654
|
[
|
|
646
655
|
...redGreenObligation(compiled),
|
|
647
656
|
...taskShapeWarnings(repo, selection, task, compiled),
|
|
657
|
+
...syncCheck.warnings,
|
|
648
658
|
],
|
|
649
659
|
problems.length === 0
|
|
650
660
|
? compiled
|
|
@@ -2400,6 +2410,9 @@ function changeClose(repo, options) {
|
|
|
2400
2410
|
}
|
|
2401
2411
|
}
|
|
2402
2412
|
|
|
2413
|
+
const syncCheck = syncGateCheck(repo, "change-close");
|
|
2414
|
+
problems.push(...syncCheck.problems);
|
|
2415
|
+
warnings.push(...syncCheck.warnings);
|
|
2403
2416
|
const status =
|
|
2404
2417
|
problems.length > 0
|
|
2405
2418
|
? "fail"
|