@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/lock.js
CHANGED
|
@@ -11,10 +11,19 @@ const RESOURCE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
|
11
11
|
const USAGE = [
|
|
12
12
|
"keel lock acquire <resource> --for <n>s|m|h|d --note <why> acquire or renew",
|
|
13
13
|
"keel lock release <resource> holder only",
|
|
14
|
-
"keel lock
|
|
14
|
+
"keel lock acquire --branch <b> [--for <d>] [--note <why>] [--break <reason>] [--push]",
|
|
15
|
+
" a branch lock kept on the remote (#526)",
|
|
16
|
+
"keel lock release --branch <b> after the branch is pushed",
|
|
17
|
+
"keel lock list [--json] live leases and fetched branch locks",
|
|
15
18
|
"Options: --repo <path>, --json. See docs/resource-lock.md.",
|
|
16
|
-
"A lease enforces nothing on Git or the filesystem.",
|
|
19
|
+
"A local lease enforces nothing on Git or the filesystem.",
|
|
17
20
|
].join("\n");
|
|
21
|
+
const { spawnSync } = require("child_process");
|
|
22
|
+
const os = require("os");
|
|
23
|
+
|
|
24
|
+
const GRACE_MS = 5 * 60 * 1000;
|
|
25
|
+
const LOCK_PREFIX = "refs/keel/lock/";
|
|
26
|
+
const LOOKUP_TIMEOUT_MS = 30000;
|
|
18
27
|
|
|
19
28
|
class LockError extends Error {}
|
|
20
29
|
|
|
@@ -180,8 +189,476 @@ function release(where, resource) {
|
|
|
180
189
|
return { lease, warnings: notify(where, lease.waiters, "lock " + resource + " released by " + lease.holder) };
|
|
181
190
|
}
|
|
182
191
|
|
|
192
|
+
|
|
193
|
+
// --- the branch lock (#526 D6-D10, D19, D22) ----------------------------------------------
|
|
194
|
+
//
|
|
195
|
+
// A lease kept as the ref refs/keel/lock/<branch> on the branch's remote. Every
|
|
196
|
+
// update is a commit whose parent is the lock commit this device observed,
|
|
197
|
+
// pushed without force, so git's own fast-forward rule lets exactly one of two
|
|
198
|
+
// devices acting on the same observation win. Exit 3 is "not authorized".
|
|
199
|
+
|
|
200
|
+
class LockRefused extends LockError {
|
|
201
|
+
constructor(message, code = 1) {
|
|
202
|
+
super(message);
|
|
203
|
+
this.code = code;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const LOCK_IDENTITY = {
|
|
208
|
+
GIT_AUTHOR_NAME: "keel lock", GIT_AUTHOR_EMAIL: "keel-lock@localhost",
|
|
209
|
+
GIT_COMMITTER_NAME: "keel lock", GIT_COMMITTER_EMAIL: "keel-lock@localhost",
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
function run(cwd, args, extraEnv = {}) {
|
|
213
|
+
const env = { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", ...extraEnv };
|
|
214
|
+
if (!env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
|
|
215
|
+
const result = spawnSync("git", args, { cwd, encoding: "utf8", env, timeout: LOOKUP_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 });
|
|
216
|
+
return {
|
|
217
|
+
ok: !result.error && result.status === 0,
|
|
218
|
+
out: String(result.stdout || "").trim(),
|
|
219
|
+
err: result.error ? (result.error.code === "ETIMEDOUT" ? `timed out after ${LOOKUP_TIMEOUT_MS / 1000} s` : result.error.message)
|
|
220
|
+
: String(result.stderr || "").trim(),
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// This machine's name in a lock (D22): written once to the chat store, or named
|
|
225
|
+
// by KEEL_DEVICE where several devices share one store.
|
|
226
|
+
function deviceId(where) {
|
|
227
|
+
if (process.env.KEEL_DEVICE && /^[A-Za-z0-9._-]{1,64}$/.test(process.env.KEEL_DEVICE)) return process.env.KEEL_DEVICE;
|
|
228
|
+
const file = path.join(where.root, "device.json");
|
|
229
|
+
try {
|
|
230
|
+
const saved = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
231
|
+
if (saved && typeof saved.id === "string" && saved.id) return saved.id;
|
|
232
|
+
} catch {
|
|
233
|
+
// first use on this machine
|
|
234
|
+
}
|
|
235
|
+
const host = (os.hostname().split(".")[0] || "host").toLowerCase().replace(/[^a-z0-9-]/g, "-").slice(0, 24) || "host";
|
|
236
|
+
const id = `${host}-${crypto.randomBytes(4).toString("hex")}`;
|
|
237
|
+
fs.mkdirSync(where.root, { recursive: true });
|
|
238
|
+
try {
|
|
239
|
+
fs.writeFileSync(file, `${JSON.stringify({ id, host: os.hostname() }, null, 2)}\n`, { flag: "wx" });
|
|
240
|
+
return id;
|
|
241
|
+
} catch (error) {
|
|
242
|
+
if (error.code !== "EEXIST") throw error;
|
|
243
|
+
return JSON.parse(fs.readFileSync(file, "utf8")).id;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function checkBranch(cwd, branch) {
|
|
248
|
+
if (!branch || !run(cwd, ["check-ref-format", "--branch", branch]).ok) {
|
|
249
|
+
throw new LockRefused(`Invalid branch ${JSON.stringify(branch)}.`, 2);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function branchRemote(cwd, branch) {
|
|
254
|
+
const configured = run(cwd, ["config", "--get", `branch.${branch}.remote`]);
|
|
255
|
+
return configured.ok && configured.out && configured.out !== "." ? configured.out : "origin";
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function parseLock(cwd, sha) {
|
|
259
|
+
if (!sha) return null;
|
|
260
|
+
const body = run(cwd, ["log", "-1", "--format=%B", sha]);
|
|
261
|
+
if (!body.ok) return null;
|
|
262
|
+
const fields = {};
|
|
263
|
+
for (const line of body.out.split("\n")) {
|
|
264
|
+
const match = line.match(/^([A-Za-z-]+): (.*)$/);
|
|
265
|
+
if (match && !(match[1] in fields)) fields[match[1]] = match[2];
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
sha, state: fields["keel-lock"] || "unknown", holder: fields.Holder || "unknown", device: fields.Device || null,
|
|
269
|
+
seq: Number(fields.Seq) || 0, expires: fields.Expires || null, head: fields.Head && fields.Head !== "none" ? fields.Head : null,
|
|
270
|
+
reason: fields.Reason || null, note: fields.Note || null, tookOver: fields["Took-over"] || null, broke: fields.Broke || null,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// One ls-remote for the branch and its lock, then a fetch of whatever the
|
|
275
|
+
// local objects lack, into refs/keel/lock/<b> and refs/remotes/<r>/<b>.
|
|
276
|
+
function observe(cwd, remote, branch) {
|
|
277
|
+
const asked = run(cwd, ["ls-remote", remote, `refs/heads/${branch}`, `${LOCK_PREFIX}${branch}`]);
|
|
278
|
+
if (!asked.ok) throw new LockRefused(`cannot verify ${remote}: ${asked.err.split("\n").pop()}`);
|
|
279
|
+
let lockSha = null;
|
|
280
|
+
let branchSha = null;
|
|
281
|
+
for (const line of asked.out.split("\n").filter(Boolean)) {
|
|
282
|
+
const [sha, ref] = line.split("\t");
|
|
283
|
+
if (ref === `${LOCK_PREFIX}${branch}`) lockSha = sha;
|
|
284
|
+
if (ref === `refs/heads/${branch}`) branchSha = sha;
|
|
285
|
+
}
|
|
286
|
+
const specs = [];
|
|
287
|
+
if (lockSha) specs.push(`+${LOCK_PREFIX}${branch}:${LOCK_PREFIX}${branch}`);
|
|
288
|
+
if (branchSha) specs.push(`+refs/heads/${branch}:refs/remotes/${remote}/${branch}`);
|
|
289
|
+
if (specs.length) {
|
|
290
|
+
const fetched = run(cwd, ["fetch", "--no-tags", "-q", remote, ...specs]);
|
|
291
|
+
if (!fetched.ok) throw new LockRefused(`cannot fetch ${remote}: ${fetched.err.split("\n").pop()}`);
|
|
292
|
+
} else {
|
|
293
|
+
run(cwd, ["update-ref", "-d", `${LOCK_PREFIX}${branch}`]);
|
|
294
|
+
}
|
|
295
|
+
return { lockSha, branchSha, lock: parseLock(cwd, lockSha) };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function isAncestor(cwd, older, newer) {
|
|
299
|
+
return run(cwd, ["merge-base", "--is-ancestor", older, newer]).ok;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function contains(cwd, tip, sha) {
|
|
303
|
+
return !sha || (Boolean(tip) && (tip === sha || isAncestor(cwd, sha, tip)));
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function short(sha) {
|
|
307
|
+
return sha ? sha.slice(0, 8) : "none";
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function describeBranchLock(branch, lock) {
|
|
311
|
+
return `${branch}: ${lock.state} by ${lock.holder}, expires ${lock.expires || "unknown"}, head ${short(lock.head)}`;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function liveFor(lock, now, grace) {
|
|
315
|
+
const expires = Date.parse(lock.expires || "");
|
|
316
|
+
return Number.isFinite(expires) && now <= expires + grace;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function authorization(cwd) {
|
|
320
|
+
const config = require("./config");
|
|
321
|
+
const read = config.readStandingAuthorization(cwd);
|
|
322
|
+
return { declared: read.declared || [], globs: read.pushGlobs || [], protectedGlobs: read.protectedPushes || [] };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function requireDeviceSync(cwd) {
|
|
326
|
+
if (!authorization(cwd).declared.includes("device-sync")) {
|
|
327
|
+
throw new LockRefused("pushing a branch lock needs `device-sync` in keel/config.yaml authorize:; nothing was pushed.", 3);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function ttlSeconds(cwd, duration) {
|
|
332
|
+
if (duration) {
|
|
333
|
+
const match = String(duration).match(/^(\d+)([smhd])$/);
|
|
334
|
+
if (!match || Number(match[1]) <= 0) throw new LockRefused(`Invalid --for duration ${JSON.stringify(duration)}: use a positive integer followed by s, m, h or d.`, 2);
|
|
335
|
+
return Number(match[1]) * { s: 1, m: 60, h: 3600, d: 86400 }[match[2]];
|
|
336
|
+
}
|
|
337
|
+
return require("./config").readSyncDeclaration(cwd).ttlSeconds;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function lockMessage(fields) {
|
|
341
|
+
const lines = [`keel-lock: ${fields.state}`, "", `Holder: ${fields.holder}`, `Device: ${fields.device}`, `Seq: ${fields.seq}`,
|
|
342
|
+
`Expires: ${fields.expires}`, `Head: ${fields.head || "none"}`];
|
|
343
|
+
if (fields.reason) lines.push(`Reason: ${fields.reason}`);
|
|
344
|
+
if (fields.note) lines.push(`Note: ${fields.note}`);
|
|
345
|
+
if (fields.tookOver) lines.push(`Took-over: ${fields.tookOver}`);
|
|
346
|
+
if (fields.broke) lines.push(`Broke: ${fields.broke}`);
|
|
347
|
+
return `${lines.join("\n")}\n`;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function pushLock(cwd, remote, branch, parent, fields) {
|
|
351
|
+
const empty = run(cwd, ["hash-object", "-t", "tree", "/dev/null"]).out;
|
|
352
|
+
const args = ["commit-tree", empty, "-m", lockMessage(fields)];
|
|
353
|
+
if (parent) args.push("-p", parent);
|
|
354
|
+
const commit = run(cwd, args, LOCK_IDENTITY);
|
|
355
|
+
if (!commit.ok) throw new LockError(`cannot write the lock commit: ${commit.err}`);
|
|
356
|
+
const pushed = run(cwd, ["push", "--porcelain", remote, `${commit.out}:${LOCK_PREFIX}${branch}`]);
|
|
357
|
+
if (!pushed.ok) {
|
|
358
|
+
if (/rejected|non-fast-forward|fetch first|stale/i.test(pushed.out + pushed.err)) {
|
|
359
|
+
const now = observe(cwd, remote, branch);
|
|
360
|
+
throw new LockRefused(`the lock of ${branch} was taken by another device first${now.lock ? `: ${describeBranchLock(branch, now.lock)}` : ""}; nothing was changed.`);
|
|
361
|
+
}
|
|
362
|
+
throw new LockRefused(`cannot push the lock of ${branch} to ${remote}: ${(pushed.err || pushed.out).split("\n").pop()}`);
|
|
363
|
+
}
|
|
364
|
+
run(cwd, ["update-ref", `${LOCK_PREFIX}${branch}`, commit.out]);
|
|
365
|
+
return commit.out;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function waitersFile(where, branch) {
|
|
369
|
+
return path.join(lockDir(where), "branches", `${encodeURIComponent(branch)}.json`);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function readWaiters(where, branch) {
|
|
373
|
+
try {
|
|
374
|
+
const rows = JSON.parse(fs.readFileSync(waitersFile(where, branch), "utf8"));
|
|
375
|
+
return Array.isArray(rows) ? rows : [];
|
|
376
|
+
} catch {
|
|
377
|
+
return [];
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function writeWaiters(where, branch, rows) {
|
|
382
|
+
fs.mkdirSync(path.dirname(waitersFile(where, branch)), { recursive: true });
|
|
383
|
+
if (rows.length) store.writeJsonAtomic(where, waitersFile(where, branch), rows);
|
|
384
|
+
else fs.rmSync(waitersFile(where, branch), { force: true });
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function roleOf(holder) {
|
|
388
|
+
const name = String(holder || "").split("@")[0];
|
|
389
|
+
return name && !name.startsWith("worktree:") && new RegExp(store.NAME_PATTERN_TEXT).test(name) ? name : null;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Pushes the branch itself, fast-forward only, where `push` allows it and it
|
|
393
|
+
// is not push-protected (D10). The repository's hooks run; a failure is said.
|
|
394
|
+
function pushBranch(cwd, remote, branch) {
|
|
395
|
+
const { declared, globs, protectedGlobs } = authorization(cwd);
|
|
396
|
+
const { globRegExp } = require("./branches");
|
|
397
|
+
if (protectedGlobs.some((glob) => globRegExp(String(glob).split("@")[0]).test(branch))) {
|
|
398
|
+
return { pushed: false, text: `${branch} is push-protected, which needs a person's answer; not pushed.` };
|
|
399
|
+
}
|
|
400
|
+
const cover = declared.includes("push") ? "push" : (globs.find((glob) => globRegExp(glob).test(branch)) ? `push:${globs.find((glob) => globRegExp(glob).test(branch))}` : null);
|
|
401
|
+
if (!cover) {
|
|
402
|
+
const named = globs.length ? globs.map((glob) => `push:${glob}`).join(", ") : "no push entry";
|
|
403
|
+
return { pushed: false, text: `${branch} is not covered by ${named}; not pushed. Declare push or push:${branch} to let Keel push it.` };
|
|
404
|
+
}
|
|
405
|
+
const pushed = run(cwd, ["push", remote, `refs/heads/${branch}:refs/heads/${branch}`]);
|
|
406
|
+
if (!pushed.ok) return { pushed: false, text: `pushing ${branch} failed: ${pushed.err || pushed.out}` };
|
|
407
|
+
return { pushed: true, text: `pushed ${branch} to ${remote} (${cover}).` };
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function acquireBranch(where, cwd, branch, options) {
|
|
411
|
+
checkBranch(cwd, branch);
|
|
412
|
+
if (options.break !== undefined && options.break !== null && !String(options.break).trim()) {
|
|
413
|
+
throw new LockRefused("--break needs a reason.", 2);
|
|
414
|
+
}
|
|
415
|
+
requireDeviceSync(cwd);
|
|
416
|
+
const seconds = ttlSeconds(cwd, options.duration);
|
|
417
|
+
const device = deviceId(where);
|
|
418
|
+
const holder = `${identity(where).holder}@${device}`;
|
|
419
|
+
const remote = branchRemote(cwd, branch);
|
|
420
|
+
const lines = [];
|
|
421
|
+
if (options.renewOnly) {
|
|
422
|
+
const seen = observe(cwd, remote, branch);
|
|
423
|
+
const lock = seen.lock;
|
|
424
|
+
if (!lock || lock.state !== "held" || lock.device !== device || !liveFor(lock, Date.now(), 0)) {
|
|
425
|
+
throw new LockRefused(`cannot renew ${branch}: ${lock ? describeBranchLock(branch, lock) : "no lock"}; lease left to lapse.`);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (options.push) {
|
|
429
|
+
const local = run(cwd, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).out;
|
|
430
|
+
if (local) {
|
|
431
|
+
const pushed = pushBranch(cwd, remote, branch);
|
|
432
|
+
if (options.renewOnly && !pushed.pushed && pushed.text.includes("failed:")) throw new LockRefused(pushed.text);
|
|
433
|
+
lines.push(pushed.text);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
const seen = observe(cwd, remote, branch);
|
|
437
|
+
const tip = run(cwd, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).out || null;
|
|
438
|
+
const lock = seen.lock;
|
|
439
|
+
const now = Date.now();
|
|
440
|
+
const ours = lock && lock.state === "held" && lock.device === device;
|
|
441
|
+
if (options.renewOnly && (!ours || !liveFor(lock, now, 0))) {
|
|
442
|
+
throw new LockRefused(`cannot renew ${branch}: ${lock ? describeBranchLock(branch, lock) : "no lock"}; lease left to lapse.`);
|
|
443
|
+
}
|
|
444
|
+
const fields = {
|
|
445
|
+
state: "held", holder, device, seq: (lock ? lock.seq : 0) + 1,
|
|
446
|
+
expires: new Date(now + seconds * 1000).toISOString(), head: seen.branchSha,
|
|
447
|
+
reason: options.note || `work on ${branch}`,
|
|
448
|
+
};
|
|
449
|
+
const others = [];
|
|
450
|
+
if (!ours) {
|
|
451
|
+
if (lock && lock.state === "held" && liveFor(lock, now, GRACE_MS)) {
|
|
452
|
+
if (!options.break) {
|
|
453
|
+
const waiters = readWaiters(where, branch);
|
|
454
|
+
const me = identity(where);
|
|
455
|
+
if (!waiters.some((row) => row.holder === holder)) writeWaiters(where, branch, [...waiters, { holder, role: me.role, worktree: me.worktree }]);
|
|
456
|
+
const told = notify(where, [{ role: roleOf(lock.holder) }], `${holder} waits for branch ${branch}`);
|
|
457
|
+
throw new LockRefused(`branch ${branch} is held by ${lock.holder}, expires ${lock.expires}, head ${short(lock.head)}; `
|
|
458
|
+
+ `you are recorded as a waiter. Take it only with --break "<reason>".${told.length ? ` ${told.join(" ")}` : ""}`);
|
|
459
|
+
}
|
|
460
|
+
fields.broke = `${lock.holder} — ${String(options.break).trim()}`;
|
|
461
|
+
} else if (lock && lock.state === "held") {
|
|
462
|
+
fields.tookOver = lock.holder;
|
|
463
|
+
others.push(`took over ${branch} from ${lock.holder}, whose lease expired ${lock.expires}: it last recorded head ${short(lock.head)}; `
|
|
464
|
+
+ `the remote ${branch} is at ${short(seen.branchSha)}.`);
|
|
465
|
+
}
|
|
466
|
+
if (!tip) throw new LockRefused(`there is no local branch ${branch}; fetch it and check it out, then acquire.`);
|
|
467
|
+
const needed = [lock && lock.state === "released" ? lock.head : null, seen.branchSha].filter(Boolean);
|
|
468
|
+
const missing = needed.find((sha) => !contains(cwd, tip, sha));
|
|
469
|
+
if (missing) {
|
|
470
|
+
throw new LockRefused(`local ${branch} at ${short(tip)} does not contain ${short(missing)}, where the previous holder finished; `
|
|
471
|
+
+ `fetch and integrate first (git pull --ff-only ${remote} ${branch}).`);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
let sha;
|
|
475
|
+
try {
|
|
476
|
+
sha = pushLock(cwd, remote, branch, seen.lockSha, fields);
|
|
477
|
+
} catch (error) {
|
|
478
|
+
// What was already said about the branch push (a failing hook's output
|
|
479
|
+
// included) is said once, ahead of why the lock push failed too.
|
|
480
|
+
if (error instanceof LockRefused && lines.length) error.message = `${lines.join("\n")}\n${error.message}`;
|
|
481
|
+
throw error;
|
|
482
|
+
}
|
|
483
|
+
writeWaiters(where, branch, readWaiters(where, branch).filter((row) => row.holder !== holder));
|
|
484
|
+
const result = { branch, remote, lock: { ...fields, sha }, renewed: Boolean(ours), messages: [...lines, ...others] };
|
|
485
|
+
if (lock && !ours) {
|
|
486
|
+
const text = fields.broke ? `branch ${branch} lock broken by ${holder}: ${fields.broke}`
|
|
487
|
+
: fields.tookOver ? `branch ${branch} taken over by ${holder} from ${lock.holder}; last head ${short(lock.head)}, remote ${short(seen.branchSha)}`
|
|
488
|
+
: `branch ${branch} acquired by ${holder}`;
|
|
489
|
+
result.warnings = notify(where, [{ role: roleOf(lock.holder) }], text);
|
|
490
|
+
}
|
|
491
|
+
return result;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function releaseBranch(where, cwd, branch, options = {}) {
|
|
495
|
+
checkBranch(cwd, branch);
|
|
496
|
+
requireDeviceSync(cwd);
|
|
497
|
+
const device = deviceId(where);
|
|
498
|
+
const remote = branchRemote(cwd, branch);
|
|
499
|
+
const seen = observe(cwd, remote, branch);
|
|
500
|
+
const lock = seen.lock;
|
|
501
|
+
if (!lock || lock.state !== "held" || lock.device !== device) {
|
|
502
|
+
throw new LockRefused(`branch ${branch} is not held by this device${lock ? `: ${describeBranchLock(branch, lock)}` : ": it has no lock"}; nothing was released.`);
|
|
503
|
+
}
|
|
504
|
+
if (Date.now() > Date.parse(lock.expires || "")) {
|
|
505
|
+
throw new LockRefused(`this device's lease on ${branch} expired at ${lock.expires}; acquire it again before releasing.`);
|
|
506
|
+
}
|
|
507
|
+
const tip = run(cwd, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).out || null;
|
|
508
|
+
const checked = require("./worktrees").listWorktrees(cwd).find((row) => row.branch === branch && fs.existsSync(row.path));
|
|
509
|
+
if (checked) {
|
|
510
|
+
const status = run(checked.path, ["status", "--porcelain=v1", "--untracked-files=all"]);
|
|
511
|
+
const dirty = status.out.split("\n").filter(Boolean).map((line) => line.slice(3));
|
|
512
|
+
if (dirty.length) throw new LockRefused(`${checked.path} has uncommitted or untracked paths: ${dirty.join(", ")}; commit and push them first.`);
|
|
513
|
+
}
|
|
514
|
+
if (tip && !(seen.branchSha && contains(cwd, seen.branchSha, tip))) {
|
|
515
|
+
throw new LockRefused(`local ${branch} at ${short(tip)} is not on the remote (remote ${short(seen.branchSha)}); run git push ${remote} ${branch} first.`);
|
|
516
|
+
}
|
|
517
|
+
const fields = {
|
|
518
|
+
state: "released", holder: lock.holder, device, seq: lock.seq + 1, expires: new Date().toISOString(),
|
|
519
|
+
head: seen.branchSha, reason: lock.reason, note: options.notePath || null,
|
|
520
|
+
};
|
|
521
|
+
const sha = pushLock(cwd, remote, branch, seen.lockSha, fields);
|
|
522
|
+
const waiters = readWaiters(where, branch);
|
|
523
|
+
writeWaiters(where, branch, []);
|
|
524
|
+
return { branch, remote, lock: { ...fields, sha }, warnings: notify(where, waiters, `branch ${branch} released by ${lock.holder} at head ${short(seen.branchSha)}`) };
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// The branch locks as last fetched, with the waiters this machine recorded.
|
|
528
|
+
function branchLocks(where, cwd) {
|
|
529
|
+
const out = run(cwd, ["for-each-ref", "--format=%(refname)%00%(objectname)", LOCK_PREFIX]).out;
|
|
530
|
+
return out.split("\n").filter(Boolean).map((line) => {
|
|
531
|
+
const [ref, sha] = line.split("\0");
|
|
532
|
+
const branch = ref.slice(LOCK_PREFIX.length);
|
|
533
|
+
return { branch, ...parseLock(cwd, sha), waiters: readWaiters(where, branch) };
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
// Automatic renewal never acquires a free, released, expired or foreign lock.
|
|
539
|
+
// Failed attempts are throttled too, so an unreachable remote cannot stall every prompt.
|
|
540
|
+
function renewHeld(where, { prompt = false, now = Date.now() } = {}) {
|
|
541
|
+
const config = require("./config").readSyncDeclaration(where.worktree);
|
|
542
|
+
if (!config.lock || !authorization(where.worktree).declared.includes("device-sync")) return [];
|
|
543
|
+
const device = existingDeviceId(where);
|
|
544
|
+
if (!device) return [];
|
|
545
|
+
const file = path.join(where.root, "lock-renewals.json");
|
|
546
|
+
const state = store.readJsonFile(file);
|
|
547
|
+
const worktrees = prompt ? [{ path: where.worktree, branch: run(where.worktree, ["symbolic-ref", "--quiet", "--short", "HEAD"]).out }]
|
|
548
|
+
: require("./worktrees").listWorktrees(where.worktree);
|
|
549
|
+
const messages = [];
|
|
550
|
+
for (const lock of branchLocks(where, where.worktree)) {
|
|
551
|
+
if (lock.state !== "held" || lock.device !== device || !liveFor(lock, now, 0)) continue;
|
|
552
|
+
const worktree = worktrees.find((row) => row.branch === lock.branch && fs.existsSync(row.path));
|
|
553
|
+
if (!worktree) continue;
|
|
554
|
+
const own = store.requireLocation(worktree.path);
|
|
555
|
+
const declaration = require("./config").readSyncDeclaration(worktree.path);
|
|
556
|
+
if (!declaration.lock || !authorization(worktree.path).declared.includes("device-sync")) continue;
|
|
557
|
+
const before = state[lock.branch] || {};
|
|
558
|
+
const renewedAt = Date.parse(lock.expires) - declaration.ttlSeconds * 1000;
|
|
559
|
+
if (prompt && now - Math.max(renewedAt, before.at || 0) <= declaration.ttlSeconds * 1000 / 3) continue;
|
|
560
|
+
let text;
|
|
561
|
+
try {
|
|
562
|
+
const result = acquireBranch(own, worktree.path, lock.branch, { renewOnly: true, push: !prompt });
|
|
563
|
+
text = result.messages.join("\n");
|
|
564
|
+
state[lock.branch] = { at: now };
|
|
565
|
+
} catch (error) {
|
|
566
|
+
text = error.message;
|
|
567
|
+
state[lock.branch] = { at: now, error: text };
|
|
568
|
+
}
|
|
569
|
+
if (!prompt && text && text !== before.error) messages.push(text);
|
|
570
|
+
}
|
|
571
|
+
store.writeJsonAtomic(where, file, state);
|
|
572
|
+
return messages;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// The completion gates' read (#526 D12): one ls-remote for the branch and its
|
|
576
|
+
// lock, no fetch, no write. Returns problems as { code, message } and warnings.
|
|
577
|
+
// The device id is read, never created: a gate writes nothing.
|
|
578
|
+
function existingDeviceId(where) {
|
|
579
|
+
if (process.env.KEEL_DEVICE && /^[A-Za-z0-9._-]{1,64}$/.test(process.env.KEEL_DEVICE)) return process.env.KEEL_DEVICE;
|
|
580
|
+
try {
|
|
581
|
+
return JSON.parse(fs.readFileSync(path.join(where.root, "device.json"), "utf8")).id || null;
|
|
582
|
+
} catch {
|
|
583
|
+
return null;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
function gateSyncCheck(repo, stage) {
|
|
588
|
+
const problems = [];
|
|
589
|
+
const warnings = [];
|
|
590
|
+
const add = (code, message) => problems.push({ code, message });
|
|
591
|
+
const remotes = run(repo, ["remote"]).out.split("\n").filter(Boolean);
|
|
592
|
+
if (!remotes.length) {
|
|
593
|
+
warnings.push("sync: lock is declared but this repository has no remote, so nothing was checked.");
|
|
594
|
+
return { problems, warnings };
|
|
595
|
+
}
|
|
596
|
+
const branch = run(repo, ["symbolic-ref", "--quiet", "--short", "HEAD"]).out;
|
|
597
|
+
if (!branch) {
|
|
598
|
+
add("sync-detached", "HEAD is detached, so no branch lock can cover this work; check out the branch and `keel lock acquire --branch <b>`.");
|
|
599
|
+
return { problems, warnings };
|
|
600
|
+
}
|
|
601
|
+
const head = run(repo, ["rev-parse", "HEAD"]).out;
|
|
602
|
+
const remote = branchRemote(repo, branch);
|
|
603
|
+
const asked = run(repo, ["ls-remote", remote, `refs/heads/${branch}`, `${LOCK_PREFIX}${branch}`]);
|
|
604
|
+
if (!asked.ok) {
|
|
605
|
+
add("sync-cannot-verify", `cannot verify ${remote}: ${asked.err.split("\n").pop()}; the branch lock and pushed state are unproven, so this gate does not pass.`);
|
|
606
|
+
return { problems, warnings };
|
|
607
|
+
}
|
|
608
|
+
let lockSha = null;
|
|
609
|
+
let remoteSha = null;
|
|
610
|
+
for (const line of asked.out.split("\n").filter(Boolean)) {
|
|
611
|
+
const [sha, ref] = line.split("\t");
|
|
612
|
+
if (ref === `${LOCK_PREFIX}${branch}`) lockSha = sha;
|
|
613
|
+
if (ref === `refs/heads/${branch}`) remoteSha = sha;
|
|
614
|
+
}
|
|
615
|
+
let where = null;
|
|
616
|
+
try {
|
|
617
|
+
where = store.locate(repo);
|
|
618
|
+
} catch {
|
|
619
|
+
where = null;
|
|
620
|
+
}
|
|
621
|
+
const device = where ? existingDeviceId(where) : null;
|
|
622
|
+
const local = run(repo, ["rev-parse", "--verify", "--quiet", `${LOCK_PREFIX}${branch}`]).out || null;
|
|
623
|
+
const acquire = `\`keel lock acquire --branch ${branch}\``;
|
|
624
|
+
if (!lockSha) {
|
|
625
|
+
add("sync-no-lock", `branch ${branch} has no lock on ${remote}; run ${acquire} first.`);
|
|
626
|
+
} else if (lockSha !== local) {
|
|
627
|
+
const now = parseLock(repo, lockSha);
|
|
628
|
+
add("sync-lock-not-held", `the lock of ${branch} on ${remote} is ${short(lockSha)}${now ? ` (${now.state} by ${now.holder})` : ""}, not the one this device last pushed (${short(local)}); `
|
|
629
|
+
+ `another device has it. Run \`keel shift resume\` or ${acquire}.`);
|
|
630
|
+
} else {
|
|
631
|
+
const lock = parseLock(repo, lockSha);
|
|
632
|
+
if (!lock || lock.state !== "held" || !device || lock.device !== device) {
|
|
633
|
+
add("sync-lock-not-held", `branch ${branch} is ${lock ? `${lock.state} by ${lock.holder}` : "locked"}, not held by this device; run ${acquire} or \`keel shift resume\`.`);
|
|
634
|
+
} else if (Date.now() > Date.parse(lock.expires || "")) {
|
|
635
|
+
add("sync-lease-expired", `this device's lease on ${branch} expired at ${lock.expires}; run ${acquire} to renew it.`);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
if (!remoteSha) {
|
|
639
|
+
add("sync-unpushed", `branch ${branch} is not on ${remote}; run git push -u ${remote} ${branch}.`);
|
|
640
|
+
} else if (remoteSha !== head) {
|
|
641
|
+
if (!run(repo, ["cat-file", "-e", `${remoteSha}^{commit}`]).ok) {
|
|
642
|
+
add("sync-remote-unknown", `${remote}/${branch} is at ${short(remoteSha)}, a commit this clone does not have, while HEAD is ${short(head)}; run git fetch ${remote} and integrate.`);
|
|
643
|
+
} else if (isAncestor(repo, remoteSha, head)) {
|
|
644
|
+
const count = run(repo, ["rev-list", "--count", `${remoteSha}..${head}`]).out;
|
|
645
|
+
add("sync-unpushed", `HEAD ${short(head)} has ${count} commit(s) ${remote} lacks (remote ${short(remoteSha)}); run git push ${remote} ${branch}.`);
|
|
646
|
+
} else if (isAncestor(repo, head, remoteSha)) {
|
|
647
|
+
if (stage === "change-close") add("sync-not-at-remote", `${remote}/${branch} is at ${short(remoteSha)}, ahead of HEAD ${short(head)}; pull before closing.`);
|
|
648
|
+
} else {
|
|
649
|
+
add("sync-remote-diverged", `HEAD ${short(head)} and ${remote}/${branch} ${short(remoteSha)} have diverged; integrate them first.`);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
if (stage === "change-close") {
|
|
653
|
+
const status = run(repo, ["status", "--porcelain=v1", "--untracked-files=all"]).out;
|
|
654
|
+
const dirty = status.split("\n").filter(Boolean).map((line) => line.slice(3));
|
|
655
|
+
if (dirty.length) add("sync-uncommitted", `uncommitted or untracked paths are not on ${remote}: ${dirty.join(", ")}.`);
|
|
656
|
+
}
|
|
657
|
+
return { problems, warnings };
|
|
658
|
+
}
|
|
659
|
+
|
|
183
660
|
function runLock(argv) {
|
|
184
|
-
const options = { repo: process.cwd(), json: false, positionals: [], duration: null, note: null };
|
|
661
|
+
const options = { repo: process.cwd(), json: false, positionals: [], duration: null, note: null, branch: null, break: null, push: false };
|
|
185
662
|
try {
|
|
186
663
|
for (let index = 0; index < argv.length; index += 1) {
|
|
187
664
|
const arg = argv[index];
|
|
@@ -189,10 +666,16 @@ function runLock(argv) {
|
|
|
189
666
|
else if (arg === "--help" || arg === "-h") {
|
|
190
667
|
process.stdout.write(USAGE + "\n");
|
|
191
668
|
return 0;
|
|
192
|
-
} else if (
|
|
669
|
+
} else if (arg === "--push") options.push = true;
|
|
670
|
+
else if (arg === "--break") {
|
|
671
|
+
const value = argv[index + 1];
|
|
672
|
+
if (!value || value.startsWith("--")) throw new LockRefused("--break needs a reason.", 2);
|
|
673
|
+
options.break = value;
|
|
674
|
+
index += 1;
|
|
675
|
+
} else if (["--repo", "--for", "--note", "--branch"].includes(arg)) {
|
|
193
676
|
const value = argv[++index];
|
|
194
677
|
if (!value || value.startsWith("--")) throw new LockError(arg + " needs a value.");
|
|
195
|
-
options[{ "--repo": "repo", "--for": "duration", "--note": "note" }[arg]] = value;
|
|
678
|
+
options[{ "--repo": "repo", "--for": "duration", "--note": "note", "--branch": "branch" }[arg]] = value;
|
|
196
679
|
} else if (arg.startsWith("-")) throw new LockError("Unknown option " + arg + ".");
|
|
197
680
|
else options.positionals.push(arg);
|
|
198
681
|
}
|
|
@@ -202,6 +685,8 @@ function runLock(argv) {
|
|
|
202
685
|
return 2;
|
|
203
686
|
}
|
|
204
687
|
const where = store.requireLocation(options.repo);
|
|
688
|
+
if (options.branch !== null) return runBranchLock(where, action, resource, extra, options);
|
|
689
|
+
if (options.break !== null || options.push) throw new LockError("--break and --push are only valid with --branch.");
|
|
205
690
|
return withMutation(where, () => {
|
|
206
691
|
const reaped = reap(where);
|
|
207
692
|
for (const text of reaped.freed) {
|
|
@@ -214,7 +699,13 @@ function runLock(argv) {
|
|
|
214
699
|
const out = (data, text) => process.stdout.write((options.json ? JSON.stringify(data, null, 2) : text) + "\n");
|
|
215
700
|
if (action === "list") {
|
|
216
701
|
const leases = liveLeases(where);
|
|
217
|
-
|
|
702
|
+
const locks = branchLocks(where, where.worktree);
|
|
703
|
+
const text = [leases.length ? leases.map(describe).join("\n") : "No live leases."];
|
|
704
|
+
if (locks.length) {
|
|
705
|
+
text.push("Branch locks, as last fetched:");
|
|
706
|
+
for (const lock of locks) text.push(describeBranchLock(lock.branch, lock) + (lock.waiters.length ? `; waiting here: ${lock.waiters.map((w) => w.holder).join(", ")}` : ""));
|
|
707
|
+
}
|
|
708
|
+
out({ leases, branchLocks: locks }, text.join("\n"));
|
|
218
709
|
} else {
|
|
219
710
|
checkResource(resource);
|
|
220
711
|
if (action === "release") {
|
|
@@ -235,10 +726,25 @@ function runLock(argv) {
|
|
|
235
726
|
} catch (error) {
|
|
236
727
|
if (error instanceof LockError || error instanceof store.ChatError) {
|
|
237
728
|
process.stderr.write("keel lock: " + error.message + "\n");
|
|
238
|
-
return 1;
|
|
729
|
+
return error instanceof LockRefused ? error.code : 1;
|
|
239
730
|
}
|
|
240
731
|
throw error;
|
|
241
732
|
}
|
|
242
733
|
}
|
|
243
734
|
|
|
244
|
-
|
|
735
|
+
function runBranchLock(where, action, resource, extra, options) {
|
|
736
|
+
if (resource !== undefined || extra.length) throw new LockRefused(`--branch names the lock; ${action} takes no resource then.`, 2);
|
|
737
|
+
if (!["acquire", "release"].includes(action)) throw new LockRefused(`--branch is for acquire and release; \`keel lock list\` shows branch locks.`, 2);
|
|
738
|
+
const cwd = where.worktree;
|
|
739
|
+
const result = action === "acquire" ? acquireBranch(where, cwd, options.branch, options) : releaseBranch(where, cwd, options.branch);
|
|
740
|
+
const text = [
|
|
741
|
+
action === "acquire" ? `${result.renewed ? "renewed" : "acquired"} branch lock ${describeBranchLock(result.branch, { ...result.lock, state: "held" })}`
|
|
742
|
+
: `released branch lock ${result.branch} at head ${short(result.lock.head)}`,
|
|
743
|
+
...(result.messages || []),
|
|
744
|
+
];
|
|
745
|
+
process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : text.join("\n")}\n`);
|
|
746
|
+
for (const warning of result.warnings || []) process.stderr.write("keel lock: " + warning + "\n");
|
|
747
|
+
return 0;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
module.exports = { renewHeld, gateSyncCheck, existingDeviceId, roleOf, LockError, liveLeases, describe, runLock, acquireBranch, releaseBranch, branchLocks, deviceId, parseLock, observe, describeBranchLock, liveFor, GRACE_MS, LOCK_PREFIX };
|
package/src/core/patrol.js
CHANGED
|
@@ -573,6 +573,7 @@ function runPatrol(argv) {
|
|
|
573
573
|
// stand until resolved, so `--since-last` sends each once (#476 D1, D2).
|
|
574
574
|
const covered = (name) => name === role || options.coverage.covers(name);
|
|
575
575
|
result.standing = [
|
|
576
|
+
...require("./sync").oldLocalOnlyRisks(where, covered, options.coverage.repositoryWide),
|
|
576
577
|
...require("./shift").handOffRisks(where, Date.now(), covered),
|
|
577
578
|
...require("./chat/notice").movedSessionRisks(where, covered),
|
|
578
579
|
];
|