@christang/keel 5.228.0 → 5.229.0

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.
@@ -0,0 +1,374 @@
1
+ "use strict";
2
+
3
+ // What exists only on this machine (#526 D1-D4): every worktree, local branch
4
+ // and stash entry of the repository that is not on the remote, read from local
5
+ // refs. It reuses the worktree listing of `keel worktrees` and its git reader,
6
+ // which never takes an optional lock, so it is safe beside a running session
7
+ // and from the tick's `/` (#524): every read names its repository.
8
+
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+ const { spawnSync } = require("child_process");
12
+ const worktrees = require("./worktrees");
13
+
14
+ const USAGE = "keel sync status [--repo <path>] [--verify] [--remote <name>] [--json]";
15
+ const LOOKUP_TIMEOUT_MS = 30000;
16
+ const { git, WorktreesError } = worktrees;
17
+
18
+ class SyncError extends Error {
19
+ constructor(message, code = 2) {
20
+ super(message);
21
+ this.code = code;
22
+ }
23
+ }
24
+
25
+ function read(cwd, args) {
26
+ return git(cwd, args, true);
27
+ }
28
+
29
+ // The repository's common directory and its main worktree, whatever worktree
30
+ // or subdirectory the caller names.
31
+ function locate(repo) {
32
+ if (!fs.existsSync(repo)) throw new SyncError(`No such directory: ${repo}`);
33
+ const top = read(repo, ["rev-parse", "--show-toplevel"]);
34
+ if (!top) throw new SyncError(`Not a git repository: ${repo}`);
35
+ const common = read(top, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
36
+ const rows = worktrees.listWorktrees(top);
37
+ return { worktree: top, common, main: rows.length ? rows[0].path : top, rows };
38
+ }
39
+
40
+ // When the remote-tracking refs were last refreshed: the newest FETCH_HEAD of
41
+ // the repository or any of its worktrees, or null when none was ever fetched.
42
+ function lastFetch(common) {
43
+ const candidates = [path.join(common, "FETCH_HEAD")];
44
+ const linked = path.join(common, "worktrees");
45
+ try {
46
+ for (const name of fs.readdirSync(linked)) candidates.push(path.join(linked, name, "FETCH_HEAD"));
47
+ } catch {
48
+ // no linked worktrees
49
+ }
50
+ let newest = null;
51
+ for (const file of candidates) {
52
+ try {
53
+ const time = fs.statSync(file).mtime;
54
+ if (!newest || time > newest) newest = time;
55
+ } catch {
56
+ // never fetched there
57
+ }
58
+ }
59
+ return newest ? newest.toISOString() : null;
60
+ }
61
+
62
+ function remotes(cwd) {
63
+ return (read(cwd, ["remote"]) || "").split("\n").filter(Boolean);
64
+ }
65
+
66
+ // Commits reachable from `sha` that no remote-tracking ref contains.
67
+ function unpushedCount(cwd, sha) {
68
+ const out = read(cwd, ["rev-list", "--count", sha, "--not", "--remotes"]);
69
+ return out === null ? 0 : Number(out.trim()) || 0;
70
+ }
71
+
72
+ function localBranches(cwd) {
73
+ return allBranches(cwd).filter((row) => row.unpushed > 0).map(({ branch, head, upstream, remote, unpushed, remoteName }) =>
74
+ ({ branch, head, upstream, remote, unpushed, remoteName }));
75
+ }
76
+
77
+ // Every local branch, with the remote it belongs to: its upstream's remote,
78
+ // else `origin` (#526 A4), and the remote-tracking ref that counterpart is.
79
+ function allBranches(cwd, override = null) {
80
+ const out = read(cwd, ["for-each-ref", "--format=%(refname:short)%00%(objectname)%00%(upstream:short)%00%(upstream:remotename)", "refs/heads/"]) || "";
81
+ const rows = [];
82
+ for (const line of out.split("\n").filter(Boolean)) {
83
+ const [branch, sha, upstream, upstreamRemote] = line.split("\0");
84
+ const remoteName = override || upstreamRemote || "origin";
85
+ const remoteRef = upstream || (read(cwd, ["rev-parse", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`]) ? `${remoteName}/${branch}` : null);
86
+ rows.push({ branch, head: sha, upstream: upstream || null, remote: remoteRef, remoteName, unpushed: unpushedCount(cwd, sha) });
87
+ }
88
+ return rows;
89
+ }
90
+
91
+ // One `git ls-remote --heads` per remote (#526 D3), limited in time and never
92
+ // prompting; it writes no ref. A failure is returned, never thrown.
93
+ function lookup(cwd, remote) {
94
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" };
95
+ if (!env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
96
+ const ran = spawnSync("git", ["ls-remote", remote, "refs/heads/*", "refs/keel/lock/*"], { cwd, encoding: "utf8", env, timeout: LOOKUP_TIMEOUT_MS });
97
+ if (ran.error || ran.status !== 0) {
98
+ const why = ran.error ? (ran.error.code === "ETIMEDOUT" ? `timed out after ${LOOKUP_TIMEOUT_MS / 1000} s` : ran.error.message)
99
+ : String(ran.stderr || "").trim().split("\n").pop() || `git ls-remote exited ${ran.status}`;
100
+ return { error: why };
101
+ }
102
+ const heads = new Map();
103
+ const locks = new Map();
104
+ for (const line of String(ran.stdout || "").split("\n").filter(Boolean)) {
105
+ const [sha, ref] = line.split("\t");
106
+ if (ref && ref.startsWith("refs/heads/")) heads.set(ref.slice("refs/heads/".length), sha);
107
+ if (ref && ref.startsWith("refs/keel/lock/")) locks.set(ref.slice("refs/keel/lock/".length), sha);
108
+ }
109
+ return { heads, locks };
110
+ }
111
+
112
+ function ancestor(cwd, older, newer) {
113
+ return read(cwd, ["merge-base", "--is-ancestor", older, newer]) !== null;
114
+ }
115
+
116
+ // How a local tip stands against the sha the remote itself reports.
117
+ function classify(cwd, local, remote) {
118
+ if (!remote) return "not-on-remote";
119
+ if (remote === local) return "same";
120
+ if (read(cwd, ["cat-file", "-e", `${remote}^{commit}`]) === null) return "unknown-to-local";
121
+ if (ancestor(cwd, remote, local)) return "remote-behind";
122
+ if (ancestor(cwd, local, remote)) return "remote-ahead";
123
+ return "diverged";
124
+ }
125
+
126
+ const SETTLED = new Set(["same", "remote-ahead"]);
127
+
128
+ function verify(cwd, override) {
129
+ const branches = allBranches(cwd, override);
130
+ const answers = new Map();
131
+ for (const name of [...new Set(branches.map((row) => row.remoteName))]) answers.set(name, lookup(cwd, name));
132
+ return {
133
+ remotes: [...answers.keys()],
134
+ branches: branches.map((row) => {
135
+ const answer = answers.get(row.remoteName);
136
+ if (answer.error) return { branch: row.branch, remote: row.remoteName, local: row.head, state: "cannot verify", error: answer.error };
137
+ const remoteSha = answer.heads.get(row.branch) || null;
138
+ const lockSha = answer.locks.get(row.branch) || null;
139
+ const fetchedLock = read(cwd, ["rev-parse", "--verify", "--quiet", `refs/keel/lock/${row.branch}`]) || null;
140
+ return {
141
+ branch: row.branch, remote: row.remoteName, local: row.head, remoteSha, state: classify(cwd, row.head, remoteSha),
142
+ lockSha, lockMoved: lockSha !== fetchedLock,
143
+ };
144
+ }),
145
+ };
146
+ }
147
+
148
+ function dirtyCount(cwd) {
149
+ const out = read(cwd, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
150
+ if (!out) return 0;
151
+ const fields = out.split("\0").filter(Boolean);
152
+ let count = 0;
153
+ for (let index = 0; index < fields.length; index += 1) {
154
+ count += 1;
155
+ if (fields[index][0] === "R" || fields[index][0] === "C") index += 1;
156
+ }
157
+ return count;
158
+ }
159
+
160
+ function localWorktrees(rows, localOnly) {
161
+ const listed = [];
162
+ for (const row of rows) {
163
+ if (!fs.existsSync(row.path)) {
164
+ listed.push({ path: row.path, missing: true, branch: row.branch });
165
+ continue;
166
+ }
167
+ const dirty = dirtyCount(row.path);
168
+ const detachedUnpushed = !row.branch && row.head ? unpushedCount(row.path, row.head) : 0;
169
+ const branchLocal = row.branch ? localOnly.has(row.branch) : false;
170
+ if (!dirty && !detachedUnpushed && !branchLocal) continue;
171
+ listed.push({
172
+ path: row.path, missing: false, branch: row.branch, head: row.head,
173
+ dirty, detachedUnpushed, localBranch: branchLocal,
174
+ });
175
+ }
176
+ return listed;
177
+ }
178
+
179
+ function stashes(cwd) {
180
+ const out = read(cwd, ["stash", "list", "--format=%gd%x00%gs%x00%ct"]) || "";
181
+ return out.split("\n").filter(Boolean).map((line) => {
182
+ const [ref, subject, time] = line.split("\0");
183
+ const match = subject.match(/^(?:WIP on|On) ([^:]+):/);
184
+ return { ref, subject, branch: match ? match[1] : null, time: new Date(Number(time) * 1000).toISOString() };
185
+ });
186
+ }
187
+
188
+ // Stable standing risks for the patrol: age decides eligibility but never
189
+ // enters the text, so the existing since-last mechanism sends each item once.
190
+ function oldLocalOnlyRisks(where, covered, repositoryWide, now = Date.now()) {
191
+ const rows = worktrees.listWorktrees(where.worktree);
192
+ const roles = JSON.parse(fs.existsSync(path.join(where.common, "keel-chat", "roles.json"))
193
+ ? fs.readFileSync(path.join(where.common, "keel-chat", "roles.json"), "utf8") : "{}");
194
+ const risks = [];
195
+ const old = (sha) => {
196
+ const times = (read(where.worktree, ["log", "--format=%ct", sha, "--not", "--remotes"]) || "")
197
+ .split("\n").filter(Boolean).map(Number).filter(Number.isFinite);
198
+ return times.length && Math.min(...times) * 1000 < now - 24 * 3600000;
199
+ };
200
+ if (remotes(where.worktree).length) {
201
+ for (const row of rows) {
202
+ const role = roles[row.path];
203
+ if (!role || !covered(role) || !row.head || !old(row.head)) continue;
204
+ risks.push(`${role}: local-only ${row.branch ? `branch ${row.branch}` : `detached head in ${row.path}`} has work only on this machine; run \`keel sync status\`.`);
205
+ }
206
+ if (repositoryWide) {
207
+ const checkedOut = new Set(rows.map((row) => row.branch).filter(Boolean));
208
+ for (const branch of localBranches(where.worktree)) {
209
+ if (!checkedOut.has(branch.branch) && old(branch.head)) {
210
+ risks.push(`local-only branch ${branch.branch} has work only on this machine; run \`keel sync status\`.`);
211
+ }
212
+ }
213
+ }
214
+ }
215
+ if (repositoryWide) {
216
+ for (const stash of stashes(where.worktree)) {
217
+ if (Date.parse(stash.time) < now - 24 * 3600000) risks.push(`local-only stash ${stash.ref} (${stash.subject}) has work only on this machine; run \`keel sync status\`.`);
218
+ }
219
+ }
220
+ return risks;
221
+ }
222
+
223
+ // The whole report, from local refs only.
224
+ function status(repo, options = {}) {
225
+ const where = locate(repo);
226
+ const hasRemote = remotes(where.worktree).length > 0;
227
+ const branches = hasRemote ? localBranches(where.worktree) : [];
228
+ const localOnly = new Set(branches.map((row) => row.branch));
229
+ const result = {
230
+ repository: where.main,
231
+ hasRemote,
232
+ lastFetch: lastFetch(where.common),
233
+ branches,
234
+ worktrees: localWorktrees(where.rows, localOnly),
235
+ stashes: stashes(where.worktree),
236
+ locks: require("./lock").branchLocks({ root: path.join(where.common, "keel-chat") }, where.worktree)
237
+ .map(({ branch, state, holder, expires, head, sha }) => ({ branch, state, holder, expires, head, sha })),
238
+ };
239
+ result.localOnly = result.branches.length + result.worktrees.length + result.stashes.length > 0;
240
+ if (options.verify && hasRemote) {
241
+ result.verify = verify(where.worktree, options.remote || null);
242
+ result.unverified = result.verify.branches.some((row) => !SETTLED.has(row.state));
243
+ } else {
244
+ result.unverified = false;
245
+ }
246
+ attachFixes(where.worktree, result);
247
+ return result;
248
+ }
249
+
250
+ // The fix for each local-only item and the `authorize:` entry that covers it
251
+ // (#526 D5). Printed, never run.
252
+ function attachFixes(cwd, result) {
253
+ let declared = [];
254
+ let globs = [];
255
+ try {
256
+ const authorization = require("./config").readStandingAuthorization(cwd);
257
+ declared = authorization.declared || [];
258
+ globs = authorization.pushGlobs || [];
259
+ } catch {
260
+ // an unreadable declaration authorizes nothing
261
+ }
262
+ const { globRegExp } = require("./branches");
263
+ const pushCover = (branch) => {
264
+ if (declared.includes("push")) return "push";
265
+ const glob = globs.find((pattern) => globRegExp(pattern).test(branch));
266
+ return glob ? `push:${glob}` : null;
267
+ };
268
+ for (const row of result.branches) {
269
+ const remote = row.remoteName || "origin";
270
+ const command = row.upstream ? `git push ${remote} ${row.branch}` : `git push -u ${remote} ${row.branch}`;
271
+ const cover = pushCover(row.branch);
272
+ row.fix = { command, authorizedBy: cover, declare: cover ? null : `push or push:${row.branch}` };
273
+ }
274
+ for (const row of result.worktrees) {
275
+ if (row.missing || !row.dirty) continue;
276
+ const commit = declared.includes("commit") ? "commit" : null;
277
+ row.fix = { command: `commit in ${row.path}, then push its branch`, authorizedBy: commit, declare: commit ? null : "commit" };
278
+ }
279
+ for (const row of result.stashes) {
280
+ row.fix = { command: `git stash pop ${row.ref} on ${row.branch || "its branch"}, then commit and push`, authorizedBy: null, declare: null };
281
+ }
282
+ }
283
+
284
+ function describeFix(fix) {
285
+ if (!fix) return [];
286
+ const cover = fix.authorizedBy ? `authorized by \`${fix.authorizedBy}\`` : fix.declare ? `not authorized; declare \`${fix.declare.replace(" or ", "` or `")}\` in keel/config.yaml authorize:` : "a person's step";
287
+ return [` fix: ${fix.command} (${cover})`];
288
+ }
289
+
290
+ function describeWorktree(row) {
291
+ if (row.missing) return `worktree ${row.path}: missing`;
292
+ const parts = [];
293
+ if (row.dirty) parts.push(`${row.dirty} uncommitted or untracked path${row.dirty === 1 ? "" : "s"}`);
294
+ if (row.detachedUnpushed) parts.push(`detached head with ${row.detachedUnpushed} commit${row.detachedUnpushed === 1 ? "" : "s"} on no remote`);
295
+ if (row.localBranch) parts.push(`on branch ${row.branch}, listed above`);
296
+ return `worktree ${row.path} (${row.branch || "detached"}): ${parts.join("; ")}`;
297
+ }
298
+
299
+ function render(result) {
300
+ const lines = [
301
+ `keel sync status: ${result.repository}`,
302
+ `Remote-tracking refs are read as of the last fetch (${result.lastFetch || "never fetched"}); Keel does not fetch.`,
303
+ ];
304
+ if (!result.hasRemote) lines.push("This repository has no remote, so unpushed commits were not checked.");
305
+ if (!result.localOnly) {
306
+ lines.push("Nothing is only on this machine.");
307
+ } else {
308
+ lines.push("Only on this machine:");
309
+ for (const row of result.branches) {
310
+ lines.push(`branch ${row.branch}: ${row.remote
311
+ ? `${row.unpushed} unpushed commit${row.unpushed === 1 ? "" : "s"} (remote ${row.remote})`
312
+ : `no remote counterpart, ${row.unpushed} commit${row.unpushed === 1 ? "" : "s"}`}`);
313
+ lines.push(...describeFix(row.fix));
314
+ }
315
+ for (const row of result.worktrees) {
316
+ lines.push(describeWorktree(row));
317
+ lines.push(...describeFix(row.fix));
318
+ }
319
+ for (const row of result.stashes) {
320
+ lines.push(`stash ${row.ref}: ${row.subject} (${row.time})`);
321
+ lines.push(...describeFix(row.fix));
322
+ }
323
+ }
324
+ if (result.locks.length) {
325
+ lines.push("Branch locks, as last fetched:");
326
+ for (const lock of result.locks) {
327
+ lines.push(`lock ${lock.branch}: ${lock.state} by ${lock.holder}, expires ${lock.expires || "unknown"}, head ${lock.head ? lock.head.slice(0, 8) : "none"}`);
328
+ }
329
+ }
330
+ if (result.verify) {
331
+ lines.push(`Verified against the remote itself (git ls-remote ${result.verify.remotes.join(", ")}):`);
332
+ for (const row of result.verify.branches) {
333
+ const shas = row.state === "cannot verify" ? row.error
334
+ : `local ${row.local.slice(0, 8)}, remote ${row.remoteSha ? row.remoteSha.slice(0, 8) : "none"}`;
335
+ lines.push(`verify ${row.branch}: ${row.state} (${shas})${row.lockMoved ? `; its lock on the remote is ${row.lockSha ? row.lockSha.slice(0, 8) : "gone"}, not the one last fetched` : ""}`);
336
+ }
337
+ }
338
+ return lines.join("\n");
339
+ }
340
+
341
+ function runSync(argv) {
342
+ const options = { repo: process.cwd(), json: false, verify: false, remote: null };
343
+ try {
344
+ const [command, ...rest] = argv;
345
+ if (command === "--help" || command === "-h" || command === undefined) {
346
+ process.stdout.write(`${USAGE}\nLists what exists only on this machine, from local refs; --verify asks the remote for its real sha. Exit 0 when nothing, 1 when something, 2 on error.\n`);
347
+ return command === undefined ? 2 : 0;
348
+ }
349
+ if (command !== "status") throw new SyncError(`Unknown subcommand ${command}. ${USAGE}`);
350
+ for (let index = 0; index < rest.length; index += 1) {
351
+ const arg = rest[index];
352
+ if (arg === "--json") options.json = true;
353
+ else if (arg === "--verify") options.verify = true;
354
+ else if (arg === "--repo" || arg === "--remote") {
355
+ const value = rest[++index];
356
+ if (!value || value.startsWith("--")) throw new SyncError(`${arg} needs a value.`);
357
+ if (arg === "--repo") options.repo = path.resolve(value);
358
+ else options.remote = value;
359
+ } else throw new SyncError(`Unknown argument ${arg}. ${USAGE}`);
360
+ }
361
+ if (options.remote && !options.verify) throw new SyncError("--remote names the remote --verify asks; pass --verify too.");
362
+ const result = status(options.repo, options);
363
+ process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : render(result)}\n`);
364
+ return result.localOnly || result.unverified ? 1 : 0;
365
+ } catch (error) {
366
+ if (error instanceof SyncError || error instanceof WorktreesError) {
367
+ process.stderr.write(`keel sync: ${error.message}\n`);
368
+ return 2;
369
+ }
370
+ throw error;
371
+ }
372
+ }
373
+
374
+ module.exports = { oldLocalOnlyRisks, SyncError, status, render, runSync, stashes, lastFetch, verify, lookup, classify, USAGE };
package/src/core/tick.js CHANGED
@@ -168,6 +168,8 @@ function wakeEnded(where, state) {
168
168
  state.woken = state.woken || {};
169
169
  const woken = [];
170
170
  for (const role of roles) {
171
+ // A managed Codex role must never fall through to the Claude CLI waker.
172
+ if (fs.existsSync(path.join(where.root, "codex-roles", `${role}.json`))) continue;
171
173
  if (notice.parkOf(where, role)) continue;
172
174
  const entry = notice.asleep(where, role);
173
175
  if (!entry || !entry.cli) continue;
@@ -211,7 +213,9 @@ function tick(where, now = new Date()) {
211
213
  const result = { patrol: null, woken: [] };
212
214
  // First, so a run that fails later still counts as a run (#510 D1).
213
215
  store.writeJsonAtomic(where, stateFile(where), { ...readState(where), last_tick: store.isoLocal(now) });
216
+ result.sync = require("./lock").renewHeld(where);
214
217
  const wakeState = readState(where);
218
+ result.codex = require("./codex-host").wakeManaged(where);
215
219
  result.woken = wakeEnded(where, wakeState);
216
220
  result.handedOver = require("./shift").handOver(where);
217
221
  if (result.woken.length) {
@@ -288,9 +292,11 @@ function tick(where, now = new Date()) {
288
292
  function render(result) {
289
293
  const woke = (result.woken || []).map((w) => `keel tick: ${w.ok ? "resumed" : "could not resume"} ${w.role}'s CLI session ${w.session} for ${w.record}`);
290
294
  const handed = (result.handedOver || []).map((h) => `keel tick: ${h.role}'s hand-off ${h.state}${h.new_session ? ` as session ${h.new_session}` : ""}${h.error ? `: ${h.error}` : ""}`);
295
+ const codex = (result.codex || []).filter(entry => entry.state !== "already-delivered")
296
+ .map(entry => `keel tick: Codex ${entry.role}: ${entry.error || entry.state}${entry.record ? ` for ${entry.record}` : ""}`);
291
297
  const quota = result.quota ? [`keel tick: ${result.quota.text}`] : [];
292
298
  const issues = result.issues ? [`keel tick: ${result.issues.text}`] : [];
293
- return [...handed, ...woke, ...quota, ...issues,...(result.patrols || [result.patrol]).map(renderPatrol)].join("\n");
299
+ return [...(result.sync || []), ...handed, ...woke, ...codex, ...quota, ...issues,...(result.patrols || [result.patrol]).map(renderPatrol)].join("\n");
294
300
  }
295
301
 
296
302
  function renderPatrol(p) {
@@ -24,11 +24,16 @@ function git(cwd, args, optional = false) {
24
24
  return String(result.stdout || "").replace(/\n$/, "");
25
25
  }
26
26
 
27
- // NUL delimiters preserve spaces, quotes and newlines in worktree paths.
27
+ // NUL delimiters preserve spaces, quotes and newlines in worktree paths. Git
28
+ // before 2.36 has no `-z` there (#526: git 2.34 refused it and `keel worktrees`
29
+ // failed outright), so it falls back to newline-separated fields, which read
30
+ // every path that holds no newline.
28
31
  function listWorktrees(repo) {
29
32
  const rows = [];
30
33
  let row = null;
31
- for (const field of git(repo, ["worktree", "list", "--porcelain", "-z"]).split("\0")) {
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");
36
+ for (const field of fields) {
32
37
  if (field.startsWith("worktree ")) {
33
38
  row = { path: field.slice(9), branch: null, head: null, locked: null, prunable: null };
34
39
  rows.push(row);
@@ -177,4 +182,4 @@ function runWorktrees(argv) {
177
182
  }
178
183
  }
179
184
 
180
- module.exports = { WorktreesError, runWorktrees, branchIssues, defaultBranch };
185
+ module.exports = { WorktreesError, runWorktrees, branchIssues, defaultBranch, listWorktrees, git };