@rarog/server 1.1.1 → 1.1.2-beta.2
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/node_modules/@rarog/shared/package.json +1 -1
- package/node_modules/@rarog/shared/src/decode.js +46 -1
- package/node_modules/@rarog/shared/src/notify-copy.js +2 -0
- package/node_modules/@rarog/shared/src/protocol/background.js +7 -0
- package/node_modules/@rarog/shared/src/protocol/context.js +57 -0
- package/node_modules/@rarog/shared/src/protocol/coordination.js +42 -0
- package/node_modules/@rarog/shared/src/protocol/dialog-live.js +117 -0
- package/node_modules/@rarog/shared/src/protocol/files.js +1 -1
- package/node_modules/@rarog/shared/src/protocol/inbox.js +6 -0
- package/node_modules/@rarog/shared/src/protocol/presence.js +47 -0
- package/node_modules/@rarog/shared/src/protocol.js +14 -146
- package/node_modules/@rarog/shared/src/rest.js +16 -1
- package/node_modules/@rarog/shared/src/sentences/dialogs.js +10 -0
- package/node_modules/@rarog/shared/src/sentences/push.js +9 -0
- package/node_modules/@rarog/shared/src/sentences/rest.js +9 -0
- package/node_modules/@rarog/shared/src/sentences/restart.js +1 -0
- package/node_modules/@rarog/shared/src/sentences/session.js +24 -0
- package/package.json +2 -2
- package/plugin/rarog/.claude-plugin/plugin.json +4 -0
- package/plugin/rarog/bin/rarog-coordinator +7 -0
- package/plugin/rarog/hooks/hooks.json +18 -0
- package/plugin/rarog/hooks/recipient.mjs +95 -0
- package/plugin/rarog/lib/coordinator.mjs +1340 -0
- package/plugin/rarog/lib/threads.mjs +350 -0
- package/plugin/rarog/skills/coordinator/SKILL.md +111 -0
- package/plugin/rarog/skills/coordinator/check-and-merge.md +46 -0
- package/plugin/rarog/skills/coordinator/close-thread.md +15 -0
- package/plugin/rarog/skills/coordinator/role.md +61 -0
- package/plugin/rarog/skills/coordinator/send-back.md +39 -0
- package/plugin/rarog/skills/coordinator/start-thread.md +43 -0
- package/server/src/bootstrap/coordination.js +49 -0
- package/server/src/bootstrap/coordinator-start.js +27 -0
- package/server/src/bootstrap/inbox.js +4 -0
- package/server/src/bootstrap/pr-status.js +15 -7
- package/server/src/bootstrap/push.js +59 -5
- package/server/src/cli/doctor-pr-status.js +10 -6
- package/server/src/companion/catalog.js +1 -1
- package/server/src/companion/index.js +2 -4
- package/server/src/config/flags.js +4 -0
- package/server/src/config-env.js +15 -0
- package/server/src/config.js +17 -3
- package/server/src/coordination/merge-events.js +86 -0
- package/server/src/coordination/merge-prompt.js +244 -0
- package/server/src/coordination/registry.js +289 -0
- package/server/src/coordination/state.js +94 -0
- package/server/src/coordination/summary.js +422 -0
- package/server/src/coordination/thread-file.js +245 -0
- package/server/src/coordination/thread-git.js +110 -0
- package/server/src/coordination/watch.js +237 -0
- package/server/src/demo/content/coordinator.js +89 -0
- package/server/src/demo/content/en.js +57 -1
- package/server/src/demo/content/pl.js +57 -1
- package/server/src/demo/control.js +4 -2
- package/server/src/demo/inbox.js +12 -0
- package/server/src/demo/mock-herdr.js +5 -4
- package/server/src/demo/review-routes.js +2 -2
- package/server/src/demo/scenarios.js +31 -17
- package/server/src/demo/seeds.js +82 -40
- package/server/src/drivers/herdr/live-dialog.js +412 -0
- package/server/src/drivers/herdr/live-step.js +261 -0
- package/server/src/drivers/herdr/pause-gate.js +60 -0
- package/server/src/drivers/herdr/pull-request-poll.js +5 -5
- package/server/src/drivers/herdr/queue-take-back.js +4 -0
- package/server/src/drivers/herdr/returned-prompt.js +4 -1
- package/server/src/drivers/herdr/screen-fallback.js +50 -0
- package/server/src/drivers/herdr/start-dialog-gate.js +136 -0
- package/server/src/drivers/herdr-driver.js +159 -77
- package/server/src/files/refusals.js +9 -2
- package/server/src/files/session-gate.js +5 -4
- package/server/src/git-branch-diff.js +194 -0
- package/server/src/herdr/argv.js +34 -3
- package/server/src/herdr/audit.js +32 -1
- package/server/src/herdr/background/cli-shapes.js +35 -15
- package/server/src/herdr/background/index.js +7 -7
- package/server/src/herdr/background/merge.js +17 -5
- package/server/src/herdr/background/notification.js +0 -4
- package/server/src/herdr/background/pull-request-files.js +53 -161
- package/server/src/herdr/background/pull-requests.js +54 -632
- package/server/src/herdr/background/queued-prompt.js +46 -0
- package/server/src/herdr/background/work.js +96 -0
- package/server/src/herdr/client.js +22 -46
- package/server/src/herdr/commands/catalog.js +11 -7
- package/server/src/herdr/commands/discover.js +33 -1
- package/server/src/herdr/commands/index.js +3 -2
- package/server/src/herdr/dialogs/copy.js +7 -0
- package/server/src/herdr/dialogs/index.js +13 -1
- package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +4 -56
- package/server/src/herdr/dialogs/live/model.js +220 -0
- package/server/src/herdr/dialogs/live/policy.js +108 -0
- package/server/src/herdr/dialogs/live/view.js +261 -0
- package/server/src/herdr/dialogs/screen/form.js +6 -4
- package/server/src/herdr/dialogs/screen/option-run.js +25 -3
- package/server/src/herdr/dialogs/screen/parse.js +3 -3
- package/server/src/herdr/dialogs/screen/signatures.js +78 -0
- package/server/src/herdr/dialogs/screen/start-dialog.js +72 -0
- package/server/src/herdr/dialogs/screen/trust-arrow.js +46 -9
- package/server/src/herdr/engines.js +96 -0
- package/server/src/herdr/history-steps.js +9 -4
- package/server/src/herdr/identity.js +20 -5
- package/server/src/herdr/jsonl-follow.js +26 -3
- package/server/src/herdr/label-code.js +104 -0
- package/server/src/herdr/label-migration.js +142 -0
- package/server/src/herdr/launcher.js +30 -5
- package/server/src/herdr/plugin-copy.js +281 -0
- package/server/src/herdr/provenance.js +80 -40
- package/server/src/herdr/session-index.js +19 -0
- package/server/src/herdr/start-dialog-wait.js +96 -0
- package/server/src/herdr/supervisor.js +49 -23
- package/server/src/herdr/types.js +1 -0
- package/server/src/herdr/workspace-resolver.js +5 -4
- package/server/src/inbox/card.js +31 -8
- package/server/src/inbox/heads.js +1 -0
- package/server/src/inbox/inbox.js +21 -4
- package/server/src/inbox/removals.js +10 -1
- package/server/src/index.js +45 -8
- package/server/src/notify/apns-payload.js +5 -3
- package/server/src/notify/content.js +64 -0
- package/server/src/notify/index.js +11 -3
- package/server/src/notify/live-activity-state.js +19 -6
- package/server/src/notify/live-activity.js +5 -2
- package/server/src/notify/policy.js +53 -13
- package/server/src/notify/ready-to-merge.js +148 -0
- package/server/src/notify/stalled-wait.js +213 -0
- package/server/src/pr-status/facts.js +87 -0
- package/server/src/pr-status/gh.js +76 -9
- package/server/src/pr-status/index.js +1 -10
- package/server/src/pr-status/source.js +20 -6
- package/server/src/pr-status/tracker.js +32 -9
- package/server/src/project-root.js +233 -0
- package/server/src/routes/sessions.js +68 -2
- package/server/src/sessions/branch-diff.js +57 -0
- package/server/src/sessions/cli-registry.js +17 -3
- package/server/src/sessions/companion-scope.js +2 -1
- package/server/src/sessions/consent-cards.js +49 -2
- package/server/src/sessions/conversation-lists.js +11 -2
- package/server/src/sessions/coordinator-start.js +172 -0
- package/server/src/sessions/demo-modules.js +1 -0
- package/server/src/sessions/demo-seeds.js +100 -0
- package/server/src/sessions/driver-events.js +68 -14
- package/server/src/sessions/herdr-lifecycle.js +11 -4
- package/server/src/sessions/interrupt-windows.js +28 -4
- package/server/src/sessions/launch-gate.js +36 -11
- package/server/src/sessions/live-dialog.js +69 -0
- package/server/src/sessions/manager.js +138 -287
- package/server/src/sessions/owner-turn.js +36 -0
- package/server/src/sessions/pr-status-link.js +64 -16
- package/server/src/sessions/seen-marks.js +31 -12
- package/server/src/sessions/session-dialog.js +82 -0
- package/server/src/sessions/session-git.js +1 -0
- package/server/src/sessions/session-scope.js +6 -5
- package/server/src/sessions/session-take-back.js +5 -0
- package/server/src/sessions/session.js +82 -10
- package/server/src/sessions/state-machine.js +13 -0
- package/server/src/sessions/state-sentences.js +87 -30
- package/server/src/sessions/test-session.js +50 -0
- package/server/src/sessions/waiting-line.js +49 -0
- package/server/src/term/herdr-backend.js +15 -12
- package/server/src/term/lifecycle.js +4 -6
- package/server/src/transcript-import.js +20 -2
- package/server/src/version.js +4 -0
- /package/server/src/{companion/asks-owner.js → asks-owner.js} +0 -0
|
@@ -0,0 +1,1340 @@
|
|
|
1
|
+
// rarog-coordinator: the only way the coordinator starts a thread, checks it, merges it into main and closes it.
|
|
2
|
+
// Every action prints one result line for the model: "ok <action>: …", "refused <action>: …" (nothing changed),
|
|
3
|
+
// "failed <action>: …" (an outcome to act on, such as a red check), "copy: …" or "error <action>: …".
|
|
4
|
+
// Exit codes: 0 ok, 1 internal error, 2 usage, 3 refused or copy, 4 failed.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
10
|
+
import {
|
|
11
|
+
THREAD_PREFIX, UUID_RE, SLUG_RE, MODES, MODEL_RE, DATA_DIR, MARKER_FILE, EXCLUDE_LINE,
|
|
12
|
+
isThreadName, cleanGitEnv, git, gitRaw, projectPaths, dataDirIgnored, dataDirTracked, readThreadFile, readThreads,
|
|
13
|
+
serializeThread, readMarker, serializeMarker, writeAtomic, processTable, sessionPids, socketAddress,
|
|
14
|
+
threadWorktreePath, pathProblem,
|
|
15
|
+
} from './threads.mjs';
|
|
16
|
+
|
|
17
|
+
const HERDR = 'herdr';
|
|
18
|
+
const EXIT = { refused: 3, copy: 3, failed: 4, usage: 2 };
|
|
19
|
+
// The owner's /rarog:coordinator as Claude Code 2.1.332 writes it to the transcript: the whole user entry is the
|
|
20
|
+
// command tags, optionally with the request in <command-args>. The tags quoted inside another prompt do not count.
|
|
21
|
+
const COMMAND_ENTRY = new RegExp('^\\s*<command-message>rarog:coordinator</command-message>\\s*'
|
|
22
|
+
+ '<command-name>/rarog:coordinator</command-name>(?:\\s*<command-args>[\\s\\S]*</command-args>)?\\s*$');
|
|
23
|
+
// A project may still keep coordinator files in .development/watki/; claim moves them to .rarog/ once.
|
|
24
|
+
const LEGACY_DIR = path.join('.development', 'watki');
|
|
25
|
+
const COPY_SENTENCE = 'This is a copy of the coordinator conversation. Write to the coordinator.';
|
|
26
|
+
const RESERVED_SLUGS = new Set(['coordinator']);
|
|
27
|
+
const MAX_GOAL = 1000;
|
|
28
|
+
|
|
29
|
+
class Outcome extends Error {
|
|
30
|
+
constructor(kind, message) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.kind = kind;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const refuse = (message) => { throw new Outcome('refused', message); };
|
|
36
|
+
const fail = (message) => { throw new Outcome('failed', message); };
|
|
37
|
+
const usage = (message) => { throw new Outcome('usage', `${message}; run "rarog-coordinator help"`); };
|
|
38
|
+
|
|
39
|
+
const notes = [];
|
|
40
|
+
|
|
41
|
+
const oneLine = (text) => String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
42
|
+
const short = (sha) => (sha ? sha.slice(0, 7) : '-');
|
|
43
|
+
const threadAddress = (name) => `"${THREAD_PREFIX}${name}"`;
|
|
44
|
+
const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
45
|
+
const real = (p) => { try { return fs.realpathSync(p); } catch { return path.resolve(p); } };
|
|
46
|
+
|
|
47
|
+
// Two locks, both directories with an owner file inside. The merge lock (see mergeLockPath) is held by check and
|
|
48
|
+
// merge (see mergeRange); the metadata lock `.rarog/metadata.lock` is held by claim and start for their whole run,
|
|
49
|
+
// so two of them never read the marker or a thread file at the same time. No call holds both. The owner file names
|
|
50
|
+
// this tool's pid, the conversation, the time and a random token; a call removes only a lock whose owner file still
|
|
51
|
+
// carries its own token. A call killed with SIGKILL (a Bash timeout) leaves its lock behind; the owner file lets
|
|
52
|
+
// status and the refusal say whether the holder still runs.
|
|
53
|
+
const LOCK_OWNER_FILE = 'owner';
|
|
54
|
+
const LOCK_STALE_MS = 30 * 60 * 1000;
|
|
55
|
+
const MERGE_LOCK_HELD = 'another check or merge of this project, or another merge into main, is running';
|
|
56
|
+
const METADATA_LOCK_HELD = 'another claim or start of this project is running; run this again after it ends';
|
|
57
|
+
const heldLocks = [];
|
|
58
|
+
|
|
59
|
+
const MERGE_LOCK_DEFAULT = 'rarog-merge.lock';
|
|
60
|
+
const MERGE_LOCK_NAME_FILE = 'merge-lock';
|
|
61
|
+
const MERGE_LOCK_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,58}\.lock$/;
|
|
62
|
+
// files git itself locks with `<file>.lock` that may not exist yet in a repository
|
|
63
|
+
const GIT_LOCKED_FILES = new Set(['index', 'config', 'packed-refs', 'shallow', 'description']);
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The merge lock is a directory in the git common directory, so a project whose own sessions already take a lock
|
|
67
|
+
* directory there before they merge into main can share it with the coordinator: the project writes that
|
|
68
|
+
* directory's name to `.rarog/merge-lock` (one line), and check and merge then wait for the same lock as the
|
|
69
|
+
* project's own merges. Without that file the lock is `rarog-merge.lock`. The name is lowercase letters, digits, `-`
|
|
70
|
+
* and `_` ending in `.lock`, and never the lock name of a file git keeps there, so the lock cannot block git itself
|
|
71
|
+
* and a stale-lock refusal never points at a directory of git. A name that breaks these rules refuses the call.
|
|
72
|
+
*/
|
|
73
|
+
function mergeLockPath(c) {
|
|
74
|
+
const file = path.join(c.data, MERGE_LOCK_NAME_FILE);
|
|
75
|
+
const unusable = (reason) => refuse(`the merge lock name in ${file} is unusable: ${reason}; write one line with the `
|
|
76
|
+
+ `name of the lock directory in ${c.common} (lowercase letters, digits, - and _, ending in .lock), or remove the `
|
|
77
|
+
+ `file to use ${MERGE_LOCK_DEFAULT}; nothing changed`);
|
|
78
|
+
let stat;
|
|
79
|
+
try {
|
|
80
|
+
stat = fs.lstatSync(file);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error.code === 'ENOENT') return path.join(c.common, MERGE_LOCK_DEFAULT);
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
if (!stat.isFile()) unusable('not a regular file (symbolic link or directory)');
|
|
86
|
+
if (stat.size > 256) unusable('larger than 256 bytes');
|
|
87
|
+
const text = fs.readFileSync(file, 'utf8').replace(/\n$/, '');
|
|
88
|
+
if (/[\n\r]/.test(text)) unusable('more than one line');
|
|
89
|
+
const name = text.trim();
|
|
90
|
+
if (!name) unusable('empty');
|
|
91
|
+
if (!MERGE_LOCK_NAME_RE.test(name)) unusable(`${JSON.stringify(name)} is not a directory name ending in .lock`);
|
|
92
|
+
const base = name.slice(0, -'.lock'.length);
|
|
93
|
+
if (GIT_LOCKED_FILES.has(base) || fs.existsSync(path.join(c.common, base))) {
|
|
94
|
+
unusable(`${JSON.stringify(name)} is the lock name of git's own ${base}`);
|
|
95
|
+
}
|
|
96
|
+
return path.join(c.common, name);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const metadataLockPath = (c) => path.join(c.data, 'metadata.lock');
|
|
100
|
+
|
|
101
|
+
function ownerToken(dir) {
|
|
102
|
+
try {
|
|
103
|
+
return /^token: (\S+)$/m.exec(fs.readFileSync(path.join(dir, LOCK_OWNER_FILE), 'utf8'))?.[1] ?? '';
|
|
104
|
+
} catch {
|
|
105
|
+
return '';
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** True while the lock directory still carries this call's token (nobody removed it and took it again). */
|
|
110
|
+
function stillHeld(held) {
|
|
111
|
+
return ownerToken(held.dir) === held.token;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function releaseLock(held) {
|
|
115
|
+
const index = heldLocks.indexOf(held);
|
|
116
|
+
if (index < 0) return;
|
|
117
|
+
heldLocks.splice(index, 1);
|
|
118
|
+
if (!stillHeld(held)) {
|
|
119
|
+
notes.push(`note: the lock ${held.dir} was replaced by another holder while this call ran; it was left in place`);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
fs.rmSync(path.join(held.dir, LOCK_OWNER_FILE), { force: true });
|
|
124
|
+
fs.rmdirSync(held.dir);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
notes.push(`note: could not remove the lock ${held.dir} (${error.code}); show this line to the owner`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function releaseLocks() {
|
|
131
|
+
while (heldLocks.length) releaseLock(heldLocks[heldLocks.length - 1]);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Takes a lock and returns its { dir, token }, or null when the directory already exists. */
|
|
135
|
+
function takeLock(dir, conversation) {
|
|
136
|
+
try {
|
|
137
|
+
fs.mkdirSync(dir);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error.code === 'EEXIST') return null;
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
const held = { dir, token: crypto.randomBytes(16).toString('hex') };
|
|
143
|
+
heldLocks.push(held);
|
|
144
|
+
fs.writeFileSync(path.join(dir, LOCK_OWNER_FILE), `pid: ${process.pid}\nconversation: ${conversation}\n`
|
|
145
|
+
+ `since: ${new Date().toISOString()}\ntoken: ${held.token}\n`, { mode: 0o600, flag: 'wx' });
|
|
146
|
+
return held;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Whether the process named in an owner file holds the lock: "running" (that pid is this tool), "gone" (no such
|
|
151
|
+
* process, or the pid now belongs to another program), "unknown" (ps could not read it).
|
|
152
|
+
*/
|
|
153
|
+
function holderState(pid) {
|
|
154
|
+
try {
|
|
155
|
+
process.kill(pid, 0);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if (error.code === 'ESRCH') return 'gone';
|
|
158
|
+
if (error.code !== 'EPERM') return 'unknown';
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
const command = execFileSync('ps', ['-o', 'command=', '-p', String(pid)], {
|
|
162
|
+
encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
|
|
163
|
+
});
|
|
164
|
+
return command.includes('coordinator.mjs') ? 'running' : 'gone';
|
|
165
|
+
} catch {
|
|
166
|
+
return 'unknown';
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* What the lock directory says about its holder; null when there is no lock. state: "held" while the holder runs
|
|
172
|
+
* (at any age) or while a lock without a named holder is younger than 30 minutes; "stale" only when the named holder
|
|
173
|
+
* is gone, or nobody is named and the lock is older than 30 minutes; "unknown" when the holder cannot be checked.
|
|
174
|
+
*/
|
|
175
|
+
function lockInfo(dir) {
|
|
176
|
+
let stat;
|
|
177
|
+
try {
|
|
178
|
+
stat = fs.statSync(dir);
|
|
179
|
+
} catch {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
const info = { since: stat.mtime.toISOString(), pid: 0, conversation: '', owner: false, holder: 'none' };
|
|
183
|
+
try {
|
|
184
|
+
const text = fs.readFileSync(path.join(dir, LOCK_OWNER_FILE), 'utf8');
|
|
185
|
+
const field = (key) => new RegExp(`^${key}: (.+)$`, 'm').exec(text)?.[1]?.trim() ?? '';
|
|
186
|
+
info.owner = true;
|
|
187
|
+
info.pid = Number(field('pid')) || 0;
|
|
188
|
+
info.conversation = field('conversation');
|
|
189
|
+
if (!Number.isNaN(Date.parse(field('since')))) info.since = field('since');
|
|
190
|
+
} catch {
|
|
191
|
+
// no owner file: a lock taken by hand (mkdir) or by an older tool
|
|
192
|
+
}
|
|
193
|
+
if (info.pid) info.holder = holderState(info.pid);
|
|
194
|
+
info.ageMs = Date.now() - Date.parse(info.since);
|
|
195
|
+
if (info.holder === 'running') info.state = 'held';
|
|
196
|
+
else if (info.holder === 'gone') info.state = 'stale';
|
|
197
|
+
else if (info.holder === 'unknown') info.state = 'unknown';
|
|
198
|
+
else info.state = info.ageMs > LOCK_STALE_MS ? 'stale' : 'held';
|
|
199
|
+
return info;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function lockText(info) {
|
|
203
|
+
const age = `${Math.max(0, Math.round(info.ageMs / 60000))} min`;
|
|
204
|
+
const state = { running: 'still running', gone: 'not running', unknown: 'state unknown: ps could not read it' };
|
|
205
|
+
const holder = info.owner
|
|
206
|
+
? `taken by pid ${info.pid || '?'} (${state[info.holder] ?? 'no pid in the owner file'}), conversation ${info.conversation || '?'}`
|
|
207
|
+
: 'no owner file (taken by hand or by another tool)';
|
|
208
|
+
return `since ${info.since} (${age} ago), ${holder}`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function lockState(info) {
|
|
212
|
+
if (!info) return 'free';
|
|
213
|
+
if (info.state === 'stale') return `STALE (ask the owner; do not remove it yourself) ${lockText(info)}`;
|
|
214
|
+
if (info.state === 'unknown') return `UNKNOWN (its holder cannot be checked; ask the owner) ${lockText(info)}`;
|
|
215
|
+
return `HELD ${lockText(info)}`;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Takes the lock or refuses with what its owner file says; never removes a lock it did not take. */
|
|
219
|
+
function acquireLock(dir, label, conversation, heldText) {
|
|
220
|
+
const held = takeLock(dir, conversation);
|
|
221
|
+
if (held) return held;
|
|
222
|
+
const info = lockInfo(dir);
|
|
223
|
+
if (info?.state === 'stale') {
|
|
224
|
+
refuse(`${label} ${dir} is STALE: ${lockText(info)}; do not remove it yourself: show this line to the owner and `
|
|
225
|
+
+ `ask whether the session that took it is gone; only the owner removes it (rm -r -- ${dir}); nothing changed`);
|
|
226
|
+
}
|
|
227
|
+
if (info?.state === 'unknown') {
|
|
228
|
+
refuse(`${label} ${dir} is in an unknown state: ${lockText(info)}; do not remove it: show this line to the owner `
|
|
229
|
+
+ 'and try again later; nothing changed');
|
|
230
|
+
}
|
|
231
|
+
return refuse(`${label} ${dir} is held${info ? `: ${lockText(info)}` : ''}; ${heldText}; nothing changed`);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
|
235
|
+
process.on(signal, () => {
|
|
236
|
+
releaseLocks();
|
|
237
|
+
process.stdout.write(`error: interrupted by ${signal}; the locks this call held were released\n`);
|
|
238
|
+
process.exit(130);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function gitTry(dir, args) {
|
|
243
|
+
const r = spawnSync('git', ['-C', dir, ...args], {
|
|
244
|
+
encoding: 'utf8', env: cleanGitEnv(), maxBuffer: 64 * 1024 * 1024,
|
|
245
|
+
});
|
|
246
|
+
return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: oneLine(r.stderr || r.error?.message) };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// ---------- environment ----------
|
|
250
|
+
|
|
251
|
+
function requireUnsandboxed() {
|
|
252
|
+
let visible = false;
|
|
253
|
+
try {
|
|
254
|
+
const out = execFileSync('ps', ['-o', 'pid=', '-p', String(process.pid)], {
|
|
255
|
+
encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
|
|
256
|
+
});
|
|
257
|
+
visible = out.trim() === String(process.pid);
|
|
258
|
+
} catch {
|
|
259
|
+
visible = false;
|
|
260
|
+
}
|
|
261
|
+
if (process.env.SANDBOX_RUNTIME === '1' || !visible) {
|
|
262
|
+
refuse('runs only outside the sandbox: call it again with dangerouslyDisableSandbox: true '
|
|
263
|
+
+ '(git worktrees, herdr and process checks fail inside it); nothing changed');
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** `<git common dir>/info/exclude`, the per-repository ignore file that is never committed. */
|
|
268
|
+
function excludeFile(c) {
|
|
269
|
+
return path.join(c.common, 'info', 'exclude');
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Adds `/.rarog/` to `.git/info/exclude` when it is not there yet (only claim calls this). Refuses to write through a
|
|
274
|
+
* symbolic link. Returns true when the line was added.
|
|
275
|
+
*/
|
|
276
|
+
function ensureExcluded(c) {
|
|
277
|
+
const file = excludeFile(c);
|
|
278
|
+
const info = path.dirname(file);
|
|
279
|
+
for (const p of [info, file]) {
|
|
280
|
+
let stat = null;
|
|
281
|
+
try {
|
|
282
|
+
stat = fs.lstatSync(p);
|
|
283
|
+
} catch (error) {
|
|
284
|
+
if (error.code !== 'ENOENT') throw error;
|
|
285
|
+
}
|
|
286
|
+
if (stat?.isSymbolicLink()) refuse(`${p} is a symbolic link; nothing changed`);
|
|
287
|
+
}
|
|
288
|
+
let text = '';
|
|
289
|
+
try {
|
|
290
|
+
text = fs.readFileSync(file, 'utf8');
|
|
291
|
+
} catch (error) {
|
|
292
|
+
if (error.code !== 'ENOENT') throw error;
|
|
293
|
+
}
|
|
294
|
+
if (text.split('\n').some((line) => line.trim() === EXCLUDE_LINE)) return false;
|
|
295
|
+
fs.mkdirSync(info, { recursive: true });
|
|
296
|
+
const separator = text === '' || text.endsWith('\n') ? '' : '\n';
|
|
297
|
+
fs.appendFileSync(file, `${separator}# coordinator files of Rarog (rarog-coordinator)\n${EXCLUDE_LINE}\n`);
|
|
298
|
+
return true;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* The project of the calling session. `.rarog/` must be ignored by git as a whole: claim adds it to
|
|
303
|
+
* `.git/info/exclude`, and every action refuses while git tracks a file under it or does not ignore it (for example
|
|
304
|
+
* a `!/.rarog/` line in `.gitignore`, which wins over the exclude file), because the coordinator files must never
|
|
305
|
+
* reach a commit.
|
|
306
|
+
*/
|
|
307
|
+
function context({ exclude = false } = {}) {
|
|
308
|
+
let paths;
|
|
309
|
+
try {
|
|
310
|
+
paths = projectPaths(process.cwd());
|
|
311
|
+
} catch (error) {
|
|
312
|
+
refuse(`not inside a git repository with a main checkout (${oneLine(error.stderr || error.message)}); nothing changed`);
|
|
313
|
+
}
|
|
314
|
+
const problem = pathProblem(paths.main, paths.threads);
|
|
315
|
+
if (problem) refuse(`the coordinator directory ${paths.data} is unsafe: ${problem}; nothing changed`);
|
|
316
|
+
if (exclude && ensureExcluded(paths)) notes.push(`note: added ${EXCLUDE_LINE} to ${excludeFile(paths)}`);
|
|
317
|
+
const tracked = dataDirTracked(paths.main);
|
|
318
|
+
if (tracked.length) {
|
|
319
|
+
refuse(`files in ${paths.data} are tracked by git: ${tracked.slice(0, 5).join(', ')}${tracked.length > 5 ? ', …' : ''}; `
|
|
320
|
+
+ 'the coordinator files must never reach a commit: show this line to the owner, who removes them from git '
|
|
321
|
+
+ `(git rm -r --cached -- ${DATA_DIR}) and commits that; nothing changed`);
|
|
322
|
+
}
|
|
323
|
+
if (!dataDirIgnored(paths.main)) {
|
|
324
|
+
refuse(`${paths.data} is not ignored by git (${exclude
|
|
325
|
+
? `${EXCLUDE_LINE} is in ${excludeFile(paths)}, but another ignore rule, such as !${EXCLUDE_LINE} in .gitignore, `
|
|
326
|
+
+ 'brings it back; remove that rule'
|
|
327
|
+
: `the owner's /rarog:coordinator runs claim, which adds ${EXCLUDE_LINE} to ${excludeFile(paths)}`}); `
|
|
328
|
+
+ 'nothing changed');
|
|
329
|
+
}
|
|
330
|
+
return paths;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function loadThreads(c) {
|
|
334
|
+
const { threads, errors } = readThreads(c.threads, c.main);
|
|
335
|
+
if (errors.length) refuse(`damaged thread files in ${c.threads}: ${errors.join('; ')}; fix or move them; nothing changed`);
|
|
336
|
+
return threads;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Whether anything (a file, a directory or a link) exists at `p`. */
|
|
340
|
+
function present(p) {
|
|
341
|
+
try {
|
|
342
|
+
fs.lstatSync(p);
|
|
343
|
+
return true;
|
|
344
|
+
} catch (error) {
|
|
345
|
+
if (error.code === 'ENOENT') return false;
|
|
346
|
+
throw error;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Moves the files of `.development/watki/` into `.rarog/`: the marker, `checks` and `init` to `.rarog/`, thread
|
|
352
|
+
* files (`<slug>.md`) and red-check marks (`<slug>.red`) to `.rarog/threads/`. Every claim runs it under the
|
|
353
|
+
* metadata lock, so a move cut short ends at the next claim; the move is done once the old directory holds no file
|
|
354
|
+
* it knows. A known file whose target already exists refuses before anything moves, naming every such file; the
|
|
355
|
+
* old directory's lock refuses too. Other files stay where they are.
|
|
356
|
+
*/
|
|
357
|
+
function migrateLegacy(c) {
|
|
358
|
+
const legacy = path.join(c.main, LEGACY_DIR);
|
|
359
|
+
if (!fs.existsSync(legacy)) return;
|
|
360
|
+
const problem = pathProblem(c.main, path.join(legacy, 'x'));
|
|
361
|
+
if (problem) refuse(`${legacy} is unsafe to move from: ${problem}; nothing changed`);
|
|
362
|
+
const entries = fs.readdirSync(legacy).sort();
|
|
363
|
+
if (entries.includes('.lock')) {
|
|
364
|
+
refuse(`${legacy}/.lock exists: a claim or start may still run there; show this line to the owner, who removes `
|
|
365
|
+
+ 'the lock once no such call runs; nothing changed');
|
|
366
|
+
}
|
|
367
|
+
const moves = [];
|
|
368
|
+
for (const name of entries) {
|
|
369
|
+
const from = path.join(legacy, name);
|
|
370
|
+
if (!fs.lstatSync(from).isFile()) continue;
|
|
371
|
+
if (name === MARKER_FILE || name === 'checks' || name === 'init') moves.push([from, path.join(c.data, name)]);
|
|
372
|
+
else if (/^[a-z0-9][a-z0-9-]{0,39}\.(?:md|red)$/.test(name)) moves.push([from, path.join(c.threads, name)]);
|
|
373
|
+
}
|
|
374
|
+
if (!moves.length) return;
|
|
375
|
+
const taken = moves.filter(([, to]) => present(to));
|
|
376
|
+
if (taken.length) {
|
|
377
|
+
refuse(`the files of ${legacy} cannot move to ${c.data}: ${taken.map(([from, to]) => `${path.basename(from)} `
|
|
378
|
+
+ `(${path.relative(c.main, to)} exists)`).join(', ')}; show this line to the owner, who keeps one copy of each `
|
|
379
|
+
+ 'and removes the other; nothing changed');
|
|
380
|
+
}
|
|
381
|
+
fs.mkdirSync(c.threads, { recursive: true });
|
|
382
|
+
for (const [from, to] of moves) fs.renameSync(from, to);
|
|
383
|
+
const left = fs.readdirSync(legacy);
|
|
384
|
+
if (!left.length) fs.rmdirSync(legacy);
|
|
385
|
+
notes.push(`note: moved ${moves.length} file(s) from ${legacy} to ${c.data}${left.length
|
|
386
|
+
? `; left in ${legacy}: ${left.join(', ')}` : `; ${legacy} removed`}`);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function identity() {
|
|
390
|
+
const id = process.env.CLAUDE_CODE_SESSION_ID ?? '';
|
|
391
|
+
const socket = process.env.CLAUDE_CODE_MESSAGING_SOCKET ?? '';
|
|
392
|
+
if (!UUID_RE.test(id)) refuse('CLAUDE_CODE_SESSION_ID is missing: run this from the Bash tool of the coordinator session');
|
|
393
|
+
if (!path.isAbsolute(socket)) {
|
|
394
|
+
refuse('CLAUDE_CODE_MESSAGING_SOCKET is missing: run this from the Bash tool of the coordinator session');
|
|
395
|
+
}
|
|
396
|
+
return { id, socket };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function pidAlive(pid) {
|
|
400
|
+
try {
|
|
401
|
+
process.kill(pid, 0);
|
|
402
|
+
return true;
|
|
403
|
+
} catch (error) {
|
|
404
|
+
return error.code === 'EPERM';
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** A messaging socket is alive while its file exists and the process named by it (<pid>.sock) runs. */
|
|
409
|
+
function socketAlive(socket) {
|
|
410
|
+
if (!fs.existsSync(socket)) return false;
|
|
411
|
+
const match = /(?:^|\/)(\d+)\.sock$/.exec(socket);
|
|
412
|
+
return match ? pidAlive(Number(match[1])) : true;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// ---------- the coordinator's own transcript (role, mode and model) ----------
|
|
416
|
+
|
|
417
|
+
function transcriptFile(id) {
|
|
418
|
+
const base = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'projects');
|
|
419
|
+
let dirs;
|
|
420
|
+
try {
|
|
421
|
+
dirs = fs.readdirSync(base);
|
|
422
|
+
} catch {
|
|
423
|
+
return null;
|
|
424
|
+
}
|
|
425
|
+
let best = null;
|
|
426
|
+
for (const dir of dirs) {
|
|
427
|
+
const file = path.join(base, dir, `${id}.jsonl`);
|
|
428
|
+
try {
|
|
429
|
+
const stat = fs.statSync(file);
|
|
430
|
+
if (stat.isFile() && (!best || stat.mtimeMs > best.mtime)) best = { file, mtime: stat.mtimeMs };
|
|
431
|
+
} catch {
|
|
432
|
+
// not in this project directory
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return best?.file ?? null;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function readEntries(file) {
|
|
439
|
+
if (!file) return [];
|
|
440
|
+
const entries = [];
|
|
441
|
+
for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
|
|
442
|
+
if (!line) continue;
|
|
443
|
+
try {
|
|
444
|
+
entries.push(JSON.parse(line));
|
|
445
|
+
} catch {
|
|
446
|
+
// a partly written last line
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
return entries;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** The latest prompt the owner typed: a user entry with origin "human", not meta, not a tool result. */
|
|
453
|
+
function lastHumanPrompt(entries) {
|
|
454
|
+
for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
455
|
+
const e = entries[i];
|
|
456
|
+
if (e?.type !== 'user' || e.isMeta === true || e.origin?.kind !== 'human') continue;
|
|
457
|
+
const content = e.message?.content;
|
|
458
|
+
if (Array.isArray(content) && content.some((part) => part?.type === 'tool_result')) continue;
|
|
459
|
+
const text = typeof content === 'string' ? content
|
|
460
|
+
: Array.isArray(content) ? content.filter((part) => part?.type === 'text').map((part) => part.text).join('\n') : '';
|
|
461
|
+
return { text, timestamp: e.timestamp ?? '' };
|
|
462
|
+
}
|
|
463
|
+
return null;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** Flags of the coordinator's own claude process (CLAUDE_PID, set by Claude Code for the Bash tool). */
|
|
467
|
+
function processFlags() {
|
|
468
|
+
const pid = process.env.CLAUDE_PID ?? '';
|
|
469
|
+
if (!/^\d+$/.test(pid)) return { found: false, model: '', mode: '' };
|
|
470
|
+
let command;
|
|
471
|
+
try {
|
|
472
|
+
command = execFileSync('ps', ['-o', 'command=', '-p', pid], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
|
|
473
|
+
} catch {
|
|
474
|
+
return { found: false, model: '', mode: '' };
|
|
475
|
+
}
|
|
476
|
+
// ps drops the shell quoting; model ids and mode names have no spaces, so splitting on blanks keeps them whole
|
|
477
|
+
const tokens = command.trim().split(/\s+/);
|
|
478
|
+
const flag = (name) => {
|
|
479
|
+
for (let i = 0; i < tokens.length; i += 1) {
|
|
480
|
+
if (tokens[i] === name) return tokens[i + 1] ?? '';
|
|
481
|
+
if (tokens[i].startsWith(`${name}=`)) return tokens[i].slice(name.length + 1);
|
|
482
|
+
}
|
|
483
|
+
return '';
|
|
484
|
+
};
|
|
485
|
+
const model = flag('--model');
|
|
486
|
+
const mode = flag('--permission-mode');
|
|
487
|
+
return { found: true, model: MODEL_RE.test(model) ? model : '', mode: MODES.has(mode) ? mode : '' };
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Settings a thread inherits. Model: only the coordinator's --model argument, kept as typed (for example
|
|
492
|
+
* "opus[1m]"; the transcript names the model without the context suffix), so without --model the thread gets the
|
|
493
|
+
* default from the owner's settings. Permission mode: the latest one in the transcript (the owner may switch it
|
|
494
|
+
* during the session), else the --permission-mode argument.
|
|
495
|
+
*/
|
|
496
|
+
function sessionSettings(entries) {
|
|
497
|
+
let transcriptMode = '';
|
|
498
|
+
for (const e of entries) {
|
|
499
|
+
if (e?.type === 'permission-mode' && MODES.has(e.permissionMode)) transcriptMode = e.permissionMode;
|
|
500
|
+
}
|
|
501
|
+
const flags = processFlags();
|
|
502
|
+
return { mode: transcriptMode || flags.mode, model: flags.model, processFound: flags.found };
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// ---------- role (coordinator marker) ----------
|
|
506
|
+
|
|
507
|
+
function markerPath(c) {
|
|
508
|
+
return path.join(c.data, MARKER_FILE);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function readRole(c, id) {
|
|
512
|
+
const r = readMarker(c.data);
|
|
513
|
+
if (r === null) return { role: 'none' };
|
|
514
|
+
if (r.error) refuse(`${markerPath(c)} is damaged (${r.error}); nothing changed`);
|
|
515
|
+
return { role: r.marker.conversation === id ? 'coordinator' : 'copy', marker: r.marker };
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function copyOutcome(c, marker) {
|
|
519
|
+
throw new Outcome('copy', `this conversation is not the coordinator of ${c.main} (the coordinator is conversation `
|
|
520
|
+
+ `${marker.conversation}). Tell the owner in their language: "${COPY_SENTENCE}" Act as an ordinary session: `
|
|
521
|
+
+ 'no threads, no merge, no SendMessage to threads; nothing changed');
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function renewText(threads) {
|
|
525
|
+
const open = threads.filter((t) => !t.merged);
|
|
526
|
+
if (!open.length) return 'no open threads';
|
|
527
|
+
return `renew notify_when_idle: SendMessage with notify_when_idle: true to each open thread: ${open.map((t) => threadAddress(t.name)).join(', ')}`;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** Every changing action: this conversation must be the one in the marker, in exactly one live process. */
|
|
531
|
+
function requireCoordinator(c, me, threads) {
|
|
532
|
+
const r = readRole(c, me.id);
|
|
533
|
+
if (r.role === 'none') {
|
|
534
|
+
refuse(`${c.main} has no coordinator yet: the owner types /rarog:coordinator in this session's terminal; nothing changed`);
|
|
535
|
+
}
|
|
536
|
+
if (r.role === 'copy') copyOutcome(c, r.marker);
|
|
537
|
+
const marker = r.marker;
|
|
538
|
+
if (marker.socket !== me.socket) {
|
|
539
|
+
if (socketAlive(marker.socket)) {
|
|
540
|
+
refuse(`another live process (${marker.socket}) runs this coordinator conversation, or ran it until a /clear; close one of them; nothing changed`);
|
|
541
|
+
}
|
|
542
|
+
writeAtomic(markerPath(c), serializeMarker({ ...marker, socket: me.socket }));
|
|
543
|
+
notes.push(`note: the coordinator process changed (resume); its notify_when_idle subscriptions died with the old process; ${renewText(threads)}`);
|
|
544
|
+
}
|
|
545
|
+
return marker;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// ---------- git helpers ----------
|
|
549
|
+
|
|
550
|
+
function listWorktrees(main) {
|
|
551
|
+
const list = [];
|
|
552
|
+
let current = null;
|
|
553
|
+
for (const line of git(main, ['worktree', 'list', '--porcelain']).split('\n')) {
|
|
554
|
+
if (line.startsWith('worktree ')) {
|
|
555
|
+
current = { path: line.slice('worktree '.length), branch: '', locked: false };
|
|
556
|
+
list.push(current);
|
|
557
|
+
} else if (current && line.startsWith('branch ')) {
|
|
558
|
+
current.branch = line.slice('branch '.length);
|
|
559
|
+
} else if (current && (line === 'locked' || line.startsWith('locked '))) {
|
|
560
|
+
current.locked = true;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
return list;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function findWorktree(main, wt) {
|
|
567
|
+
const target = real(wt);
|
|
568
|
+
return listWorktrees(main).find((w) => real(w.path) === target) ?? null;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
function statusEntries(dir, extra) {
|
|
572
|
+
const parts = gitRaw(dir, ['status', '--porcelain=v1', '-z', ...extra]).split('\0');
|
|
573
|
+
const entries = [];
|
|
574
|
+
for (let i = 0; i < parts.length; i += 1) {
|
|
575
|
+
const part = parts[i];
|
|
576
|
+
if (!part) continue;
|
|
577
|
+
const code = part.slice(0, 2);
|
|
578
|
+
entries.push({ code, file: part.slice(3) });
|
|
579
|
+
if (code[0] === 'R' || code[0] === 'C') i += 1;
|
|
580
|
+
}
|
|
581
|
+
return entries;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/** Changes in the main checkout, without the directories of registered worktrees (they show as untracked). */
|
|
585
|
+
function mainCheckoutChanges(c) {
|
|
586
|
+
const mainReal = real(c.main);
|
|
587
|
+
const worktreeDirs = new Set(listWorktrees(c.main)
|
|
588
|
+
.map((w) => path.relative(mainReal, real(w.path)))
|
|
589
|
+
.filter((rel) => rel && !rel.startsWith('..') && !path.isAbsolute(rel))
|
|
590
|
+
.map((rel) => `${rel}/`));
|
|
591
|
+
return statusEntries(c.main, ['--untracked-files=all'])
|
|
592
|
+
.filter((e) => !(e.code === '??' && worktreeDirs.has(e.file)))
|
|
593
|
+
.map((e) => e.file);
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
function mainSha(c) {
|
|
597
|
+
const r = gitTry(c.main, ['rev-parse', '--verify', '-q', 'refs/heads/main']);
|
|
598
|
+
if (!r.ok) refuse(`${c.main} has no local branch main; nothing changed`);
|
|
599
|
+
return r.out;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// ---------- herdr ----------
|
|
603
|
+
|
|
604
|
+
function herdr(args) {
|
|
605
|
+
const r = spawnSync(HERDR, args, { encoding: 'utf8', timeout: 120_000, maxBuffer: 64 * 1024 * 1024 });
|
|
606
|
+
if (r.error) return { ok: false, err: oneLine(r.error.message) };
|
|
607
|
+
if (r.status !== 0) return { ok: false, err: oneLine(`${r.stderr ?? ''} ${r.stdout ?? ''}`) || `exit ${r.status}` };
|
|
608
|
+
let json = null;
|
|
609
|
+
try {
|
|
610
|
+
json = JSON.parse(r.stdout);
|
|
611
|
+
} catch {
|
|
612
|
+
// some commands print no JSON
|
|
613
|
+
}
|
|
614
|
+
return { ok: true, json };
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function herdrAgents() {
|
|
618
|
+
const r = herdr(['agent', 'list']);
|
|
619
|
+
if (!r.ok) refuse(`cannot read the herdr agent list (${r.err}); nothing changed`);
|
|
620
|
+
const agents = r.json?.result?.agents;
|
|
621
|
+
if (!Array.isArray(agents)) refuse('the herdr agent list has no result.agents; nothing changed');
|
|
622
|
+
return agents;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** The thread's pane: by conversation id, or by the worktree it works in (after /clear the id differs). */
|
|
626
|
+
function findThreadAgent(agents, t) {
|
|
627
|
+
const bySession = agents.find((a) => a?.agent_session?.value === t.session);
|
|
628
|
+
if (bySession) return bySession;
|
|
629
|
+
const wt = real(t.worktree);
|
|
630
|
+
return agents.find((a) => a?.agent === 'claude' && typeof a.foreground_cwd === 'string' && real(a.foreground_cwd) === wt)
|
|
631
|
+
?? null;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
const isBusy = (agent) => agent && (agent.agent_status === 'working' || agent.agent_status === 'blocked');
|
|
635
|
+
|
|
636
|
+
function requireThreadIdle(t) {
|
|
637
|
+
const agent = findThreadAgent(herdrAgents(), t);
|
|
638
|
+
if (isBusy(agent)) {
|
|
639
|
+
refuse(`thread ${threadAddress(t.name)} is ${agent.agent_status === 'blocked' ? 'waiting at a dialog for the owner (herdr: blocked)' : 'working (herdr: working)'}; `
|
|
640
|
+
+ 'nothing changed; try again when it is idle');
|
|
641
|
+
}
|
|
642
|
+
return agent;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// ---------- project files: checks and init ----------
|
|
646
|
+
|
|
647
|
+
function readLines(c, name) {
|
|
648
|
+
let text;
|
|
649
|
+
try {
|
|
650
|
+
text = fs.readFileSync(path.join(c.data, name), 'utf8');
|
|
651
|
+
} catch (error) {
|
|
652
|
+
if (error.code === 'ENOENT') return null;
|
|
653
|
+
throw error;
|
|
654
|
+
}
|
|
655
|
+
return text.split('\n').map((line) => line.trim()).filter((line) => line && !line.startsWith('#'));
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* True when the project has a gitleaks configuration (`.gitleaks.toml` in the main checkout) and no check line runs
|
|
660
|
+
* gitleaks, so a thread could bring a token to main unseen; status says so and the skill proposes the scan.
|
|
661
|
+
*/
|
|
662
|
+
function secretScanMissing(c, checks) {
|
|
663
|
+
try {
|
|
664
|
+
if (!fs.lstatSync(path.join(c.main, '.gitleaks.toml')).isFile()) return false;
|
|
665
|
+
} catch {
|
|
666
|
+
return false;
|
|
667
|
+
}
|
|
668
|
+
return !(checks ?? []).some((line) => /\bgitleaks\b/.test(line));
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function requireChecks(c) {
|
|
672
|
+
const lines = readLines(c, 'checks');
|
|
673
|
+
if (!lines || !lines.length) {
|
|
674
|
+
refuse(`no checks configured: write the project's check commands, one per line, to ${path.join(c.data, 'checks')} `
|
|
675
|
+
+ '(they run in the thread worktree); nothing changed');
|
|
676
|
+
}
|
|
677
|
+
return lines;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function runLines(lines, cwd, env) {
|
|
681
|
+
for (const line of lines) {
|
|
682
|
+
const r = spawnSync('/bin/bash', ['-c', line], { cwd, env, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
|
|
683
|
+
if (r.status !== 0) {
|
|
684
|
+
const output = `${r.stdout ?? ''}${r.stderr ?? ''}`.split('\n').filter(Boolean).slice(-15);
|
|
685
|
+
return { line, status: r.status ?? r.signal ?? oneLine(r.error?.message), output };
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return null;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// ---------- threads ----------
|
|
692
|
+
|
|
693
|
+
function resolveThread(c, threads, arg) {
|
|
694
|
+
if (!arg) usage('the thread name is required');
|
|
695
|
+
let name = arg.trim();
|
|
696
|
+
if (name.startsWith(THREAD_PREFIX)) name = name.slice(THREAD_PREFIX.length);
|
|
697
|
+
const thread = threads.find((t) => t.name === name) ?? threads.find((t) => t.slug === name);
|
|
698
|
+
if (!thread) {
|
|
699
|
+
const open = threads.filter((t) => !t.merged).map((t) => threadAddress(t.name)).join(', ') || 'none';
|
|
700
|
+
refuse(`no thread named "${name}" in ${c.threads} (open threads: ${open}); nothing changed`);
|
|
701
|
+
}
|
|
702
|
+
return thread;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
function freshThread(c, t) {
|
|
706
|
+
const r = readThreadFile(t.file, t.slug, c.main);
|
|
707
|
+
if (r.error) refuse(`${t.file} became damaged (${r.error}); nothing changed`);
|
|
708
|
+
return r.thread;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/** Rebase state directories that exist in the worktree (git's rebase-merge and rebase-apply). */
|
|
712
|
+
function rebaseStateDirs(wt) {
|
|
713
|
+
return ['rebase-merge', 'rebase-apply']
|
|
714
|
+
.map((name) => git(wt, ['rev-parse', '--path-format=absolute', '--git-path', name]))
|
|
715
|
+
.filter((dir) => fs.existsSync(dir));
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
function readStateFile(dir, name) {
|
|
719
|
+
try {
|
|
720
|
+
return fs.readFileSync(path.join(dir, name), 'utf8').trim();
|
|
721
|
+
} catch {
|
|
722
|
+
return '';
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/** What changed in the thread worktree since `head` was checked out: branch, HEAD, tracked files; '' when nothing. */
|
|
727
|
+
function threadChanges(wt, t, head) {
|
|
728
|
+
const changes = [];
|
|
729
|
+
const branch = gitTry(wt, ['symbolic-ref', '-q', 'HEAD']).out;
|
|
730
|
+
if (branch !== `refs/heads/${t.branch}`) changes.push(`the worktree is on ${branch || 'a detached HEAD'}, not ${t.branch}`);
|
|
731
|
+
const now = gitTry(wt, ['rev-parse', 'HEAD']).out;
|
|
732
|
+
if (now !== head) changes.push(`HEAD ${short(head)} -> ${short(now)}`);
|
|
733
|
+
const tracked = statusEntries(wt, ['--untracked-files=no']).map((e) => e.file);
|
|
734
|
+
if (tracked.length) changes.push(`tracked files modified: ${tracked.join(', ')}`);
|
|
735
|
+
return changes.join('; ');
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
function rebaseAndCheck(c, t, checks, verb) {
|
|
739
|
+
requireThreadIdle(t);
|
|
740
|
+
const wt = t.worktree;
|
|
741
|
+
const entry = findWorktree(c.main, wt);
|
|
742
|
+
if (!entry) refuse(`thread worktree ${wt} is missing; nothing changed`);
|
|
743
|
+
if (entry.branch !== `refs/heads/${t.branch}`) refuse(`thread worktree ${wt} is not on branch ${t.branch}; nothing changed`);
|
|
744
|
+
if (rebaseStateDirs(wt).length) {
|
|
745
|
+
refuse(`a rebase is in progress in ${wt}; finish it there or run git rebase --abort; nothing changed`);
|
|
746
|
+
}
|
|
747
|
+
const tracked = statusEntries(wt, ['--untracked-files=no']).map((e) => e.file);
|
|
748
|
+
if (tracked.length) {
|
|
749
|
+
refuse(`thread ${threadAddress(t.name)} has uncommitted changes (${tracked.join(', ')}); ask the thread to commit; nothing changed`);
|
|
750
|
+
}
|
|
751
|
+
const before = git(wt, ['rev-parse', 'HEAD']);
|
|
752
|
+
const base = mainSha(c);
|
|
753
|
+
if (git(wt, ['rev-list', '--count', `${base}..${before}`]) === '0') {
|
|
754
|
+
refuse(`thread ${threadAddress(t.name)} has no commits ahead of main; nothing to ${verb}`);
|
|
755
|
+
}
|
|
756
|
+
// main takes only a linear branch: a merge commit would reach main as it is, and a rebase would drop it together
|
|
757
|
+
// with the changes made only in its conflict resolution
|
|
758
|
+
const merges = git(wt, ['rev-list', '--merges', `${base}..${before}`]).split('\n').filter(Boolean);
|
|
759
|
+
if (merges.length) {
|
|
760
|
+
refuse(`thread ${threadAddress(t.name)} has merge commits in the thread branch (${merges.length}: `
|
|
761
|
+
+ `${merges.map(short).join(', ')}); main takes only a branch without merge commits: ask the thread to rebase `
|
|
762
|
+
+ `its commits onto main without merge commits; nothing changed; nothing to ${verb}`);
|
|
763
|
+
}
|
|
764
|
+
let rebased = false;
|
|
765
|
+
if (!gitTry(wt, ['merge-base', '--is-ancestor', base, before]).ok) {
|
|
766
|
+
rebased = true;
|
|
767
|
+
const r = gitTry(wt, ['rebase', '--no-rebase-merges', base]);
|
|
768
|
+
if (!r.ok) {
|
|
769
|
+
// abort only the rebase this call started: its state names our onto and our starting commit
|
|
770
|
+
const dirs = rebaseStateDirs(wt);
|
|
771
|
+
const own = dirs.length === 1 && readStateFile(dirs[0], 'onto') === base
|
|
772
|
+
&& readStateFile(dirs[0], 'orig-head') === before;
|
|
773
|
+
if (!own && dirs.length) {
|
|
774
|
+
refuse(`git rebase did not start in ${wt} (${r.err}): a rebase this call did not start is in progress there; `
|
|
775
|
+
+ 'it was not aborted; ask the thread to finish or abort it; nothing changed');
|
|
776
|
+
}
|
|
777
|
+
if (!own) refuse(`git rebase onto main ${short(base)} did not start in ${wt} (${r.err}); nothing changed`);
|
|
778
|
+
const conflicts = gitTry(wt, ['diff', '--name-only', '--diff-filter=U']).out.split('\n').filter(Boolean);
|
|
779
|
+
const abort = gitTry(wt, ['rebase', '--abort']);
|
|
780
|
+
const after = gitTry(wt, ['rev-parse', 'HEAD']).out;
|
|
781
|
+
const where = after === before ? `branch back at ${short(before)}`
|
|
782
|
+
: `BUT the branch is at ${short(after)} instead of ${short(before)} (${abort.err || 'abort did not restore it'})`;
|
|
783
|
+
fail(`rebase of ${threadAddress(t.name)} onto main ${short(base)} hit a conflict in ${conflicts.join(', ') || 'unknown files'}; `
|
|
784
|
+
+ `rebase aborted, ${where}; checked unchanged; nothing reached main; send the thread back with the conflicting files`);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
const head = git(wt, ['rev-parse', 'HEAD']);
|
|
788
|
+
const env = cleanGitEnv({ RAROG_MAIN: c.main, RAROG_WORKTREE: wt, RAROG_SLUG: t.slug, RAROG_BASE: base, RAROG_HEAD: head });
|
|
789
|
+
const red = runLines(checks, wt, env);
|
|
790
|
+
const rebaseText = rebased ? `rebased onto main ${short(base)}` : `already on main ${short(base)}`;
|
|
791
|
+
// the result belongs to `head` only when the checks saw exactly that commit: same branch, same HEAD, no tracked
|
|
792
|
+
// file changed (by the thread or by a check); otherwise neither checked nor the red mark is recorded
|
|
793
|
+
const changed = threadChanges(wt, t, head);
|
|
794
|
+
if (changed) {
|
|
795
|
+
fail(`thread changed during the checks: ${threadAddress(t.name)} (${changed}); the result does not belong to `
|
|
796
|
+
+ `${short(head)}${red ? ` (the check \`${red.line}\` also failed)` : ''}; checked unchanged; nothing reached main; `
|
|
797
|
+
+ 'tell the owner; when the thread is idle, check again');
|
|
798
|
+
}
|
|
799
|
+
const left = statusEntries(wt, ['--untracked-files=all']).filter((e) => e.code === '??').map((e) => e.file);
|
|
800
|
+
const fresh = freshThread(c, t);
|
|
801
|
+
const redFile = path.join(c.threads, `${t.slug}.red`);
|
|
802
|
+
if (red) {
|
|
803
|
+
let previousRed = '';
|
|
804
|
+
try {
|
|
805
|
+
previousRed = fs.readFileSync(redFile, 'utf8').trim();
|
|
806
|
+
} catch {
|
|
807
|
+
// first red check of this thread
|
|
808
|
+
}
|
|
809
|
+
let checkedText = fresh.checked ? `checked kept at ${short(fresh.checked)}` : 'checked stays empty';
|
|
810
|
+
if (fresh.checked && (fresh.checked === head || previousRed === head)) {
|
|
811
|
+
writeAtomic(t.file, serializeThread({ ...fresh, checked: '' }));
|
|
812
|
+
checkedText = `checked cleared (the check failed again on ${short(head)})`;
|
|
813
|
+
}
|
|
814
|
+
writeAtomic(redFile, `${head}\n`);
|
|
815
|
+
const tail = red.output.length ? ` | output tail: ${red.output.map(oneLine).join(' / ').slice(-600)}` : '';
|
|
816
|
+
fail(`check \`${red.line}\` failed (exit ${red.status}) on ${threadAddress(t.name)} at ${short(head)} (${rebaseText}); `
|
|
817
|
+
+ `branch kept at ${short(head)} with all its commits; ${checkedText}; files left in the worktree: `
|
|
818
|
+
+ `${left.join(', ') || 'none'}; nothing reached main; send the thread back with the failing check${tail}`);
|
|
819
|
+
}
|
|
820
|
+
writeAtomic(t.file, serializeThread({ ...fresh, checked: head }));
|
|
821
|
+
fs.rmSync(redFile, { force: true });
|
|
822
|
+
const commits = git(wt, ['rev-list', '--count', `${base}..${head}`]);
|
|
823
|
+
const files = git(wt, ['diff', '--name-only', base, head]).split('\n').filter(Boolean).length;
|
|
824
|
+
return { head, base, rebaseText, commits, files, left };
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** Closes the thread's pane and removes its worktree; never when it works or has files. Returns { done, text }. */
|
|
828
|
+
function closeThread(c, t) {
|
|
829
|
+
const wt = t.worktree;
|
|
830
|
+
let entry = findWorktree(c.main, wt);
|
|
831
|
+
if (entry) {
|
|
832
|
+
const files = statusEntries(wt, ['--untracked-files=all']).map((e) => e.file);
|
|
833
|
+
if (files.length) {
|
|
834
|
+
return { done: false, text: `panel and worktree kept: the worktree has uncommitted or untracked files (${files.join(', ')})` };
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
let agents;
|
|
838
|
+
try {
|
|
839
|
+
agents = herdrAgents();
|
|
840
|
+
} catch (error) {
|
|
841
|
+
return { done: false, text: `panel and worktree kept: ${error.message}` };
|
|
842
|
+
}
|
|
843
|
+
const agent = findThreadAgent(agents, t);
|
|
844
|
+
if (isBusy(agent)) return { done: false, text: `panel and worktree kept: the thread is ${agent.agent_status} in herdr` };
|
|
845
|
+
let closed = '';
|
|
846
|
+
if (agent) {
|
|
847
|
+
const r = herdr(['pane', 'close', agent.pane_id]);
|
|
848
|
+
if (!r.ok) return { done: false, text: `panel and worktree kept: herdr pane close ${agent.pane_id} failed (${r.err})` };
|
|
849
|
+
closed = `panel ${agent.pane_id} closed, `;
|
|
850
|
+
}
|
|
851
|
+
let pids = [];
|
|
852
|
+
for (let i = 0; i < 30; i += 1) {
|
|
853
|
+
pids = sessionPids(processTable(), t.session);
|
|
854
|
+
if (!pids.length) break;
|
|
855
|
+
sleep(500);
|
|
856
|
+
}
|
|
857
|
+
if (pids.length) return { done: false, text: `${closed}worktree kept: the thread process (pid ${pids.join(', ')}) still runs` };
|
|
858
|
+
entry = findWorktree(c.main, wt);
|
|
859
|
+
if (!entry) return { done: true, text: `${closed}worktree already removed, branch ${t.branch} kept` };
|
|
860
|
+
if (entry.locked) {
|
|
861
|
+
const unlock = gitTry(c.main, ['worktree', 'unlock', wt]);
|
|
862
|
+
if (!unlock.ok) return { done: false, text: `${closed}worktree kept: git worktree unlock failed (${unlock.err})` };
|
|
863
|
+
}
|
|
864
|
+
const removed = gitTry(c.main, ['worktree', 'remove', wt]);
|
|
865
|
+
if (!removed.ok) return { done: false, text: `${closed}worktree kept: git worktree remove failed (${removed.err})` };
|
|
866
|
+
return { done: true, text: `${closed || 'no panel was open, '}worktree removed, branch ${t.branch} kept` };
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
// ---------- actions ----------
|
|
870
|
+
|
|
871
|
+
function actionClaim() {
|
|
872
|
+
requireUnsandboxed();
|
|
873
|
+
const me = identity();
|
|
874
|
+
const c = context({ exclude: true });
|
|
875
|
+
fs.mkdirSync(c.data, { recursive: true });
|
|
876
|
+
// everything below reads the marker and the thread files under the metadata lock
|
|
877
|
+
acquireLock(metadataLockPath(c), 'metadata lock', me.id, METADATA_LOCK_HELD);
|
|
878
|
+
migrateLegacy(c);
|
|
879
|
+
const threads = loadThreads(c);
|
|
880
|
+
const r = readRole(c, me.id);
|
|
881
|
+
const transcript = transcriptFile(me.id);
|
|
882
|
+
const entries = readEntries(transcript);
|
|
883
|
+
const { mode, model } = sessionSettings(entries);
|
|
884
|
+
const settings = `mode ${mode || 'unknown'}, model ${model || 'unknown'}`;
|
|
885
|
+
const write = () => writeAtomic(markerPath(c), serializeMarker({
|
|
886
|
+
conversation: me.id, socket: me.socket, since: new Date().toISOString(), mode, model,
|
|
887
|
+
}));
|
|
888
|
+
if (r.role === 'coordinator') {
|
|
889
|
+
const changed = r.marker.socket !== me.socket;
|
|
890
|
+
if (changed && socketAlive(r.marker.socket)) {
|
|
891
|
+
refuse(`another live process (${r.marker.socket}) runs this coordinator conversation, or ran it until a /clear; close one of them; nothing changed`);
|
|
892
|
+
}
|
|
893
|
+
write();
|
|
894
|
+
const tail = changed ? `; the process changed since the last claim (resume): ${renewText(threads)}` : '';
|
|
895
|
+
return `this session is the coordinator of ${c.main} (conversation ${me.id}, ${settings})${tail}`;
|
|
896
|
+
}
|
|
897
|
+
if (!transcript) {
|
|
898
|
+
refuse(`cannot find this conversation's transcript (projects/*/${me.id}.jsonl) to see the owner's /rarog:coordinator; nothing changed`);
|
|
899
|
+
}
|
|
900
|
+
const prompt = lastHumanPrompt(entries);
|
|
901
|
+
const typed = prompt !== null && COMMAND_ENTRY.test(prompt.text)
|
|
902
|
+
&& (r.role === 'none' || Date.parse(prompt.timestamp) > Date.parse(r.marker.since));
|
|
903
|
+
if (!typed) {
|
|
904
|
+
if (r.role === 'copy') copyOutcome(c, r.marker);
|
|
905
|
+
refuse('the coordinator role needs /rarog:coordinator typed by the owner as the latest prompt of this conversation; '
|
|
906
|
+
+ 'nothing changed');
|
|
907
|
+
}
|
|
908
|
+
// A new conversation takes the role only from a coordinator whose process is gone. After /clear the process (and
|
|
909
|
+
// its socket) stays the same while the conversation id changes: /clear ends the coordinator, so this is a copy too.
|
|
910
|
+
if (r.role === 'copy' && (r.marker.socket === me.socket || socketAlive(r.marker.socket))) copyOutcome(c, r.marker);
|
|
911
|
+
write();
|
|
912
|
+
const from = r.role === 'copy'
|
|
913
|
+
? ` (took over from conversation ${r.marker.conversation}, whose process is gone)`
|
|
914
|
+
: '';
|
|
915
|
+
return `this session is now the coordinator of ${c.main} (conversation ${me.id}, ${settings})${from}; ${renewText(threads)}`;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
function threadLine(c, t, agents, procs) {
|
|
919
|
+
const entry = findWorktree(c.main, t.worktree);
|
|
920
|
+
const head = gitTry(c.main, ['rev-parse', '--verify', '-q', `refs/heads/${t.branch}`]).out;
|
|
921
|
+
let worktree = 'missing';
|
|
922
|
+
if (entry) {
|
|
923
|
+
const files = statusEntries(t.worktree, ['--untracked-files=all']).map((e) => e.file);
|
|
924
|
+
worktree = files.length ? `changes (${files.join(', ')})` : 'clean';
|
|
925
|
+
}
|
|
926
|
+
const agent = agents ? findThreadAgent(agents, t) : null;
|
|
927
|
+
const herdrState = !agents ? 'unknown' : agent ? `${agent.agent_status} in ${agent.pane_id}` : 'not running';
|
|
928
|
+
const pids = sessionPids(procs, t.session);
|
|
929
|
+
const address = pids.map(socketAddress).find(Boolean) ?? '-';
|
|
930
|
+
const state = t.merged ? 'merged' : t.checked && t.checked === head ? 'checked (head = checked)' : 'open';
|
|
931
|
+
return `thread ${threadAddress(t.name)} slug=${t.slug} state=${state} head=${short(head)} checked=${short(t.checked)} `
|
|
932
|
+
+ `merged=${short(t.merged)} worktree=${worktree} herdr=${herdrState} pid=${pids.join(',') || '-'} address=${address}`;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
function actionStatus() {
|
|
936
|
+
requireUnsandboxed();
|
|
937
|
+
const c = context();
|
|
938
|
+
const threads = loadThreads(c);
|
|
939
|
+
const id = process.env.CLAUDE_CODE_SESSION_ID ?? '';
|
|
940
|
+
let role = 'unknown (not called from a Claude Code session)';
|
|
941
|
+
if (UUID_RE.test(id)) {
|
|
942
|
+
const r = readRole(c, id);
|
|
943
|
+
role = r.role === 'coordinator' ? 'coordinator (this conversation)'
|
|
944
|
+
: r.role === 'copy' ? `copy (the coordinator is conversation ${r.marker.conversation})` : 'none (no coordinator yet)';
|
|
945
|
+
}
|
|
946
|
+
const checks = readLines(c, 'checks');
|
|
947
|
+
let agents = null;
|
|
948
|
+
let herdrError = '';
|
|
949
|
+
try {
|
|
950
|
+
agents = herdrAgents();
|
|
951
|
+
} catch (error) {
|
|
952
|
+
herdrError = error.message;
|
|
953
|
+
}
|
|
954
|
+
const procs = processTable();
|
|
955
|
+
const open = threads.filter((t) => !t.merged).length;
|
|
956
|
+
const metadata = lockInfo(metadataLockPath(c));
|
|
957
|
+
const head = `role ${role}; main checkout ${c.main}; merge lock ${lockState(lockInfo(mergeLockPath(c)))}; `
|
|
958
|
+
+ `${metadata ? `metadata lock ${lockState(metadata)}; ` : ''}`
|
|
959
|
+
+ `checks ${checks ? `${checks.length} command(s)` : 'MISSING'}; `
|
|
960
|
+
+ `${secretScanMissing(c, checks) ? 'secret scan MISSING (the project has .gitleaks.toml and no check line runs '
|
|
961
|
+
+ 'gitleaks); ' : ''}threads ${open} open of ${threads.length}`
|
|
962
|
+
+ `${agents ? '' : `; herdr unreadable (${herdrError})`}`;
|
|
963
|
+
return [head, ...threads.map((t) => threadLine(c, t, agents, procs))].join('\n');
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
function herdrName(slug, session) {
|
|
967
|
+
return `t-${slug}`.slice(0, 27).replace(/-+$/, '') + `-${session.slice(0, 4)}`;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
function actionStart(opt) {
|
|
971
|
+
let name = (opt.name ?? '').trim();
|
|
972
|
+
if (name.startsWith(THREAD_PREFIX)) name = name.slice(THREAD_PREFIX.length);
|
|
973
|
+
if (/[;`$&|<>\\'"]/.test(name)) {
|
|
974
|
+
refuse(`thread name ${JSON.stringify(name)} contains shell characters; use ASCII letters, digits, hyphens and single spaces; nothing changed`);
|
|
975
|
+
}
|
|
976
|
+
if (!isThreadName(name)) {
|
|
977
|
+
refuse(`thread name ${JSON.stringify(name)} is outside the alphabet: ASCII letters, digits, hyphens, single spaces, `
|
|
978
|
+
+ 'at most 24 characters and 4 words; nothing changed');
|
|
979
|
+
}
|
|
980
|
+
const slug = opt.slug ?? name.toLowerCase().replace(/ /g, '-');
|
|
981
|
+
if (!SLUG_RE.test(slug) || RESERVED_SLUGS.has(slug)) {
|
|
982
|
+
refuse(`slug ${JSON.stringify(slug)} is not usable (lowercase letters, digits and hyphens, at most 40, not "coordinator"); nothing changed`);
|
|
983
|
+
}
|
|
984
|
+
const goal = oneLine(opt.goal);
|
|
985
|
+
requireUnsandboxed();
|
|
986
|
+
const c = context();
|
|
987
|
+
const me = identity();
|
|
988
|
+
if (!fs.existsSync(c.data)) {
|
|
989
|
+
refuse(`${c.main} has no coordinator yet: the owner types /rarog:coordinator in this session's terminal; nothing changed`);
|
|
990
|
+
}
|
|
991
|
+
// the whole start (thread file, worktree, panel) runs under the metadata lock, so two starts of one thread cannot
|
|
992
|
+
// write two session ids or open two panels; the thread files are read only after the lock is taken
|
|
993
|
+
acquireLock(metadataLockPath(c), 'metadata lock', me.id, METADATA_LOCK_HELD);
|
|
994
|
+
const threads = loadThreads(c);
|
|
995
|
+
requireCoordinator(c, me, threads);
|
|
996
|
+
const sameName = threads.find((t) => t.name === name && t.slug !== slug);
|
|
997
|
+
if (sameName) refuse(`the name "${name}" belongs to thread ${sameName.slug}; choose another name; nothing changed`);
|
|
998
|
+
let thread = threads.find((t) => t.slug === slug) ?? null;
|
|
999
|
+
if (thread?.merged) refuse(`thread ${slug} was merged at ${short(thread.merged)}; choose another name; nothing changed`);
|
|
1000
|
+
if (thread && thread.name !== name) refuse(`slug ${slug} belongs to thread "${thread.name}"; nothing changed`);
|
|
1001
|
+
if (!thread && !goal) usage('--goal "<the owner\'s sentence>" is required for a new thread');
|
|
1002
|
+
if (goal.length > MAX_GOAL) refuse(`the goal is longer than ${MAX_GOAL} characters; shorten it; nothing changed`);
|
|
1003
|
+
const workspace = process.env.HERDR_WORKSPACE_ID ?? '';
|
|
1004
|
+
if (!/^[A-Za-z0-9:_-]+$/.test(workspace)) refuse('HERDR_WORKSPACE_ID is missing: the coordinator must run in a herdr pane; nothing changed');
|
|
1005
|
+
const agents = herdrAgents();
|
|
1006
|
+
const entries = readEntries(transcriptFile(me.id));
|
|
1007
|
+
const settings = sessionSettings(entries);
|
|
1008
|
+
const mode = settings.mode || 'default';
|
|
1009
|
+
if (!settings.mode) {
|
|
1010
|
+
notes.push('note: the permission mode was found neither in the transcript nor in --permission-mode; the thread starts in mode default');
|
|
1011
|
+
}
|
|
1012
|
+
if (!settings.processFound) {
|
|
1013
|
+
notes.push('note: the coordinator process (CLAUDE_PID) was not found; the thread starts without --model (default model)');
|
|
1014
|
+
}
|
|
1015
|
+
const base = mainSha(c);
|
|
1016
|
+
const wt = threadWorktreePath(c.main, slug);
|
|
1017
|
+
const wtProblem = pathProblem(c.main, wt);
|
|
1018
|
+
if (wtProblem) refuse(`the thread worktree path ${wt} is unsafe: ${wtProblem}; nothing changed`);
|
|
1019
|
+
|
|
1020
|
+
// 1. worktree on branch <slug> from local main (finishes a branch left without worktree by a sandboxed call)
|
|
1021
|
+
let entry = findWorktree(c.main, wt);
|
|
1022
|
+
if (entry && entry.branch !== `refs/heads/${slug}`) refuse(`${wt} is a worktree on ${entry.branch || 'a detached HEAD'}, not ${slug}; nothing changed`);
|
|
1023
|
+
if (!entry) {
|
|
1024
|
+
if (fs.existsSync(wt)) refuse(`${wt} exists but is not a git worktree; nothing changed`);
|
|
1025
|
+
const branch = gitTry(c.main, ['rev-parse', '--verify', '-q', `refs/heads/${slug}`]);
|
|
1026
|
+
let added;
|
|
1027
|
+
if (branch.ok) {
|
|
1028
|
+
const own = git(c.main, ['rev-list', '--count', `${base}..${branch.out}`]);
|
|
1029
|
+
if (!thread && own !== '0') refuse(`branch ${slug} already exists with ${own} commits not on main; choose another name; nothing changed`);
|
|
1030
|
+
if (!thread && branch.out !== base) {
|
|
1031
|
+
// compare-and-swap: moves the branch only while it still points where it was read, so a commit made on it
|
|
1032
|
+
// in the meantime is never discarded
|
|
1033
|
+
const moved = gitTry(c.main, ['update-ref', `refs/heads/${slug}`, base, branch.out]);
|
|
1034
|
+
if (!moved.ok) {
|
|
1035
|
+
refuse(`branch ${slug} moved while start read it (it was ${short(branch.out)}) or cannot be set to main `
|
|
1036
|
+
+ `(${moved.err}); nothing changed; choose another name or run start again`);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
added = gitTry(c.main, ['worktree', 'add', wt, slug]);
|
|
1040
|
+
} else {
|
|
1041
|
+
if (thread) refuse(`thread file ${thread.file} exists but branch ${slug} is gone; nothing changed`);
|
|
1042
|
+
added = gitTry(c.main, ['worktree', 'add', '-b', slug, wt, base]);
|
|
1043
|
+
}
|
|
1044
|
+
if (!added.ok) refuse(`git worktree add ${wt} failed (${added.err}); call again with dangerouslyDisableSandbox: true`);
|
|
1045
|
+
entry = findWorktree(c.main, wt);
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// 2. project init and the thread file (written only after init succeeds, so a retry runs init again)
|
|
1049
|
+
if (!thread) {
|
|
1050
|
+
const init = readLines(c, 'init') ?? [];
|
|
1051
|
+
const red = runLines(init, wt, cleanGitEnv({ RAROG_MAIN: c.main, RAROG_WORKTREE: wt, RAROG_SLUG: slug, RAROG_BASE: base }));
|
|
1052
|
+
if (red) {
|
|
1053
|
+
fail(`init \`${red.line}\` failed (exit ${red.status}) in ${wt}: ${red.output.map(oneLine).join(' / ').slice(-400)}; `
|
|
1054
|
+
+ 'worktree kept, no thread file, no panel; fix it and run start again');
|
|
1055
|
+
}
|
|
1056
|
+
fs.mkdirSync(c.threads, { recursive: true });
|
|
1057
|
+
thread = {
|
|
1058
|
+
slug, file: path.join(c.threads, `${slug}.md`), name, session: crypto.randomUUID(), branch: slug, worktree: wt,
|
|
1059
|
+
base: git(c.main, ['merge-base', base, slug]), checked: '', merged: '',
|
|
1060
|
+
body: `Goal: ${goal}\nNext step: send the brief\nLast report: none`,
|
|
1061
|
+
};
|
|
1062
|
+
writeAtomic(thread.file, serializeThread(thread));
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// 3. panel: a new herdr tab in the main checkout, claude entering the worktree with --worktree
|
|
1066
|
+
// A thread pane that waits at a startup dialog may lack agent_session in herdr; its process and argv still carry
|
|
1067
|
+
// the session id, and a second panel with the same --session-id must never start.
|
|
1068
|
+
const running = agents.find((a) => a?.agent_session?.value === thread.session)
|
|
1069
|
+
?? agents.find((a) => Array.isArray(a?.argv) && a.argv.includes(thread.session)) ?? null;
|
|
1070
|
+
if (running?.agent_status === 'blocked') {
|
|
1071
|
+
fail(`the thread panel ${running.pane_id} waits at a dialog (herdr: blocked); answer it in herdr, then run start again; `
|
|
1072
|
+
+ 'no second panel opened; brief not sent');
|
|
1073
|
+
}
|
|
1074
|
+
const pids = sessionPids(processTable(), thread.session);
|
|
1075
|
+
if (!running && pids.length) {
|
|
1076
|
+
fail(`the thread process (pid ${pids.join(', ')}, session ${thread.session}) already runs, but herdr does not list it `
|
|
1077
|
+
+ 'as an agent: it probably waits at a startup dialog in its panel; answer it there, then run start again; '
|
|
1078
|
+
+ 'no second panel opened; brief not sent');
|
|
1079
|
+
}
|
|
1080
|
+
let pane = running?.pane_id;
|
|
1081
|
+
if (!running) {
|
|
1082
|
+
const clash = agents.find((a) => a?.terminal_title_stripped === `${THREAD_PREFIX}${name}`);
|
|
1083
|
+
if (clash) refuse(`another herdr pane (${clash.pane_id}) already shows the title "${THREAD_PREFIX}${name}"; choose another name; nothing changed in herdr`);
|
|
1084
|
+
const resume = transcriptFile(thread.session) !== null;
|
|
1085
|
+
const tab = herdr(['tab', 'create', '--workspace', workspace, '--cwd', c.main, '--label', `${THREAD_PREFIX}${name}`, '--no-focus']);
|
|
1086
|
+
const result = tab.json?.result ?? {};
|
|
1087
|
+
const tabId = result.tab?.tab_id ?? result.tab_id;
|
|
1088
|
+
pane = result.root_pane?.pane_id ?? result.pane?.pane_id ?? result.pane_id;
|
|
1089
|
+
if (!tab.ok || !tabId || !pane) refuse(`herdr tab create failed (${tab.err ?? 'no tab or pane id in the answer'}); worktree and thread file kept; run start again`);
|
|
1090
|
+
const claudeArgs = ['--worktree', slug, resume ? '--resume' : '--session-id', thread.session, '--name', `${THREAD_PREFIX}${name}`];
|
|
1091
|
+
if (settings.model) claudeArgs.push('--model', settings.model);
|
|
1092
|
+
claudeArgs.push('--permission-mode', mode);
|
|
1093
|
+
let started = null;
|
|
1094
|
+
let lastError = '';
|
|
1095
|
+
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
1096
|
+
const r = herdr(['agent', 'start', herdrName(slug, thread.session), '--kind', 'claude', '--pane', pane, '--timeout', '60000', '--', ...claudeArgs]);
|
|
1097
|
+
if (r.ok) {
|
|
1098
|
+
started = r;
|
|
1099
|
+
break;
|
|
1100
|
+
}
|
|
1101
|
+
lastError = r.err;
|
|
1102
|
+
if (!/agent_pane_busy/.test(lastError)) break;
|
|
1103
|
+
sleep(500);
|
|
1104
|
+
}
|
|
1105
|
+
if (!started) {
|
|
1106
|
+
if (/agent_not_ready/.test(lastError)) {
|
|
1107
|
+
fail(`the thread panel ${pane} started but waits at a dialog (${lastError}); answer it in herdr, then run start again; brief not sent`);
|
|
1108
|
+
}
|
|
1109
|
+
herdr(['tab', 'close', tabId]);
|
|
1110
|
+
fail(`herdr agent start failed (${lastError}); the new tab was closed; worktree and thread file kept; run start again; brief not sent`);
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
// 4. the thread must be in its worktree before the brief goes out
|
|
1115
|
+
let found = null;
|
|
1116
|
+
for (let i = 0; i < 40; i += 1) {
|
|
1117
|
+
found = herdrAgents().find((a) => a?.agent_session?.value === thread.session) ?? null;
|
|
1118
|
+
if (found && typeof found.foreground_cwd === 'string' && real(found.foreground_cwd) === real(wt)) break;
|
|
1119
|
+
sleep(500);
|
|
1120
|
+
}
|
|
1121
|
+
if (!found || real(found.foreground_cwd ?? '') !== real(wt)) {
|
|
1122
|
+
fail(`the thread is not in its worktree (herdr foreground_cwd ${found?.foreground_cwd ?? 'unknown'}, expected ${wt}); `
|
|
1123
|
+
+ `brief not sent; panel ${pane} left for inspection`);
|
|
1124
|
+
}
|
|
1125
|
+
if (real(found.cwd ?? '') !== real(c.main)) {
|
|
1126
|
+
notes.push(`note: the thread panel's cwd is ${found.cwd}, not the main checkout; Rarog would list it as another project`);
|
|
1127
|
+
}
|
|
1128
|
+
const how = running ? 'was already running' : 'started';
|
|
1129
|
+
return `thread ${threadAddress(name)} ${how}: slug ${slug}, session ${thread.session}, pane ${found.pane_id}, worktree ${wt}, `
|
|
1130
|
+
+ `base ${short(thread.base)}, mode ${mode}, model ${settings.model || 'default'}; next: SendMessage the brief to `
|
|
1131
|
+
+ `${threadAddress(name)} with notify_when_idle: true`;
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
function heldText(ms) {
|
|
1135
|
+
const seconds = Math.max(0, Math.round(ms / 1000));
|
|
1136
|
+
return seconds < 60 ? `${seconds} s` : `${Math.floor(seconds / 60)} min ${seconds % 60} s`;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
/**
|
|
1140
|
+
* The whole range under the merge lock, in this one function: take the lock, then for a merge the clean main
|
|
1141
|
+
* checkout, then the rebase onto main and the checks (rebaseAndCheck), then for a merge the fast-forward of main.
|
|
1142
|
+
* Check and merge take the same lock, so a check never rebases a thread that a merge is rebasing and the other way
|
|
1143
|
+
* round. Holding the lock for a shorter part of this range is a change of this function alone. Returns the result
|
|
1144
|
+
* of the checks, for a merge also main before and after, and the time the lock was held.
|
|
1145
|
+
*/
|
|
1146
|
+
function mergeRange(c, t, me, checks, merge) {
|
|
1147
|
+
const verb = merge ? 'merge' : 'check';
|
|
1148
|
+
const lock = acquireLock(mergeLockPath(c), 'merge lock', me.id,
|
|
1149
|
+
`${MERGE_LOCK_HELD}; ${merge ? 'send Merge again later' : 'check again later'}`);
|
|
1150
|
+
const since = Date.now();
|
|
1151
|
+
let done = false;
|
|
1152
|
+
try {
|
|
1153
|
+
if (merge) {
|
|
1154
|
+
const branch = gitTry(c.main, ['symbolic-ref', '-q', 'HEAD']).out;
|
|
1155
|
+
if (branch !== 'refs/heads/main') refuse(`the main checkout ${c.main} is on ${branch || 'a detached HEAD'}, not main; nothing changed`);
|
|
1156
|
+
const dirty = mainCheckoutChanges(c);
|
|
1157
|
+
if (dirty.length) {
|
|
1158
|
+
refuse(`the main checkout ${c.main} has uncommitted or untracked files: ${dirty.join(', ')}; `
|
|
1159
|
+
+ 'find out whose they are before merging; nothing changed');
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
const r = rebaseAndCheck(c, t, checks, verb);
|
|
1163
|
+
if (!merge) {
|
|
1164
|
+
done = true;
|
|
1165
|
+
return { r, heldMs: Date.now() - since };
|
|
1166
|
+
}
|
|
1167
|
+
const dirtyAfter = mainCheckoutChanges(c);
|
|
1168
|
+
if (dirtyAfter.length) {
|
|
1169
|
+
fail(`the main checkout got files during the check (${dirtyAfter.join(', ')}); checked=${short(r.head)} saved; nothing reached main`);
|
|
1170
|
+
}
|
|
1171
|
+
const before = mainSha(c);
|
|
1172
|
+
if (before !== r.base) {
|
|
1173
|
+
fail(`main moved during the check (${short(r.base)} -> ${short(before)}); checked=${short(r.head)} saved; nothing reached main; `
|
|
1174
|
+
+ 'the owner sends Merge again to rebase and check once more');
|
|
1175
|
+
}
|
|
1176
|
+
// right before the fast-forward: git merge works on the checkout's current branch, so it must still be main;
|
|
1177
|
+
// the lock must still be this call's; the range that reaches main must have no merge commit
|
|
1178
|
+
const branchNow = gitTry(c.main, ['symbolic-ref', '-q', 'HEAD']).out;
|
|
1179
|
+
if (branchNow !== 'refs/heads/main') {
|
|
1180
|
+
fail(`the main checkout ${c.main} switched to ${branchNow || 'a detached HEAD'} during the checks, not main; `
|
|
1181
|
+
+ `checked=${short(r.head)} saved; nothing reached main; show this line to the owner`);
|
|
1182
|
+
}
|
|
1183
|
+
if (!stillHeld(lock)) {
|
|
1184
|
+
fail(`the merge lock ${lock.dir} was taken over by another holder during the checks; checked=${short(r.head)} saved; `
|
|
1185
|
+
+ 'nothing reached main; the owner sends Merge again');
|
|
1186
|
+
}
|
|
1187
|
+
const merges = git(c.main, ['rev-list', '--merges', '--count', `${before}..${r.head}`]);
|
|
1188
|
+
if (merges !== '0') fail(`merge commits in the thread branch (${merges}) between main and ${short(r.head)}; nothing reached main`);
|
|
1189
|
+
// --no-squash: a branch.main.mergeOptions or merge config with --squash would change the index without main
|
|
1190
|
+
const ff = gitTry(c.main, ['merge', '--ff-only', '--no-squash', r.head]);
|
|
1191
|
+
if (!ff.ok) fail(`git merge --ff-only ${short(r.head)} failed (${ff.err}); nothing reached main`);
|
|
1192
|
+
const after = mainSha(c);
|
|
1193
|
+
const headAfter = gitTry(c.main, ['rev-parse', 'HEAD']).out;
|
|
1194
|
+
const branchAfter = gitTry(c.main, ['symbolic-ref', '-q', 'HEAD']).out;
|
|
1195
|
+
const tracked = statusEntries(c.main, ['--untracked-files=no']).map((e) => e.file);
|
|
1196
|
+
if (after === r.head) writeAtomic(t.file, serializeThread({ ...freshThread(c, t), checked: r.head, merged: after }));
|
|
1197
|
+
if (after !== r.head || headAfter !== r.head || branchAfter !== 'refs/heads/main' || tracked.length) {
|
|
1198
|
+
throw new Error(`after git merge --ff-only ${short(r.head)}: main is ${short(after)} (was ${short(before)}), `
|
|
1199
|
+
+ `the main checkout is on ${branchAfter || 'a detached HEAD'} at ${short(headAfter)}, tracked changes in it: `
|
|
1200
|
+
+ `${tracked.join(', ') || 'none'}; expected main, HEAD = ${short(r.head)} and a clean checkout; `
|
|
1201
|
+
+ `${after === r.head ? `the thread file records merged=${short(after)}` : 'the thread file is unchanged'}; `
|
|
1202
|
+
+ 'show this line to the owner and change nothing');
|
|
1203
|
+
}
|
|
1204
|
+
done = true;
|
|
1205
|
+
return { r, before, after, heldMs: Date.now() - since };
|
|
1206
|
+
} finally {
|
|
1207
|
+
releaseLock(lock);
|
|
1208
|
+
if (!done) notes.push(`note: the merge lock was held for ${heldText(Date.now() - since)}`);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
function actionCheck(arg) {
|
|
1213
|
+
requireUnsandboxed();
|
|
1214
|
+
const c = context();
|
|
1215
|
+
const me = identity();
|
|
1216
|
+
const threads = loadThreads(c);
|
|
1217
|
+
requireCoordinator(c, me, threads);
|
|
1218
|
+
const t = resolveThread(c, threads, arg);
|
|
1219
|
+
if (t.merged) refuse(`thread ${threadAddress(t.name)} is already merged at ${short(t.merged)}; nothing changed`);
|
|
1220
|
+
const checks = requireChecks(c);
|
|
1221
|
+
const { r, heldMs } = mergeRange(c, t, me, checks, false);
|
|
1222
|
+
return `thread ${threadAddress(t.name)} checked=${short(r.head)} (${r.rebaseText}): checks passed, ${r.commits} commits and `
|
|
1223
|
+
+ `${r.files} files ahead of main; files left in the worktree: ${r.left.join(', ') || 'none'}; `
|
|
1224
|
+
+ `merge lock held for ${heldText(heldMs)}; ready for the owner's "Merge: ${t.name}"`;
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
function actionMerge(arg) {
|
|
1228
|
+
requireUnsandboxed();
|
|
1229
|
+
const c = context();
|
|
1230
|
+
const me = identity();
|
|
1231
|
+
const threads = loadThreads(c);
|
|
1232
|
+
requireCoordinator(c, me, threads);
|
|
1233
|
+
const t = resolveThread(c, threads, arg);
|
|
1234
|
+
if (t.merged) refuse(`thread ${threadAddress(t.name)} is already merged at ${short(t.merged)}; nothing changed`);
|
|
1235
|
+
const checks = requireChecks(c);
|
|
1236
|
+
const { r, before, after, heldMs } = mergeRange(c, t, me, checks, true);
|
|
1237
|
+
const mergeCommits = git(c.main, ['rev-list', '--merges', '--count', `${before}..${after}`]);
|
|
1238
|
+
const subject = git(c.main, ['log', '-1', '--format=%s', after]);
|
|
1239
|
+
const line = `thread ${threadAddress(t.name)} merged by fast-forward: main ${short(before)}..${short(after)} `
|
|
1240
|
+
+ `(now ${short(after)} "${subject}"), ${r.commits} commits, ${mergeCommits} merge commits, not pushed; `
|
|
1241
|
+
+ `merge lock held for ${heldText(heldMs)}`;
|
|
1242
|
+
let cleanup;
|
|
1243
|
+
try {
|
|
1244
|
+
cleanup = closeThread(c, t).text;
|
|
1245
|
+
} catch (error) {
|
|
1246
|
+
cleanup = `panel and worktree kept: ${oneLine(error.message)}`;
|
|
1247
|
+
}
|
|
1248
|
+
return `${line}; cleanup: ${cleanup}`;
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
function actionClose(arg) {
|
|
1252
|
+
requireUnsandboxed();
|
|
1253
|
+
const c = context();
|
|
1254
|
+
const me = identity();
|
|
1255
|
+
const threads = loadThreads(c);
|
|
1256
|
+
requireCoordinator(c, me, threads);
|
|
1257
|
+
const t = resolveThread(c, threads, arg);
|
|
1258
|
+
if (!t.merged) refuse(`thread ${threadAddress(t.name)} is not merged; only merged threads are closed; nothing changed`);
|
|
1259
|
+
const r = closeThread(c, t);
|
|
1260
|
+
if (!r.done) fail(`thread ${threadAddress(t.name)}: ${r.text}`);
|
|
1261
|
+
return `thread ${threadAddress(t.name)}: ${r.text}`;
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
function actionNote(arg, opt) {
|
|
1265
|
+
if (opt.next === undefined && opt.report === undefined) usage('--next "<text>" or --report "<text>" is required');
|
|
1266
|
+
requireUnsandboxed();
|
|
1267
|
+
const c = context();
|
|
1268
|
+
const me = identity();
|
|
1269
|
+
const threads = loadThreads(c);
|
|
1270
|
+
requireCoordinator(c, me, threads);
|
|
1271
|
+
const t = resolveThread(c, threads, arg);
|
|
1272
|
+
let body = freshThread(c, t).body;
|
|
1273
|
+
const set = (label, value) => {
|
|
1274
|
+
const text = `${label}: ${oneLine(value).slice(0, MAX_GOAL)}`;
|
|
1275
|
+
const pattern = new RegExp(`^${label}:.*$`, 'm');
|
|
1276
|
+
body = pattern.test(body) ? body.replace(pattern, () => text) : `${body.replace(/\n+$/, '')}\n${text}`;
|
|
1277
|
+
};
|
|
1278
|
+
if (opt.next !== undefined) set('Next step', opt.next);
|
|
1279
|
+
if (opt.report !== undefined) set('Last report', opt.report);
|
|
1280
|
+
writeAtomic(t.file, serializeThread({ ...freshThread(c, t), body }));
|
|
1281
|
+
return `thread ${threadAddress(t.name)}: notes updated`;
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
const HELP = `rarog-coordinator <action> (always with dangerouslyDisableSandbox: true)
|
|
1285
|
+
claim take or confirm the coordinator role (after /rarog:coordinator);
|
|
1286
|
+
adds /.rarog/ to .git/info/exclude; under the metadata lock
|
|
1287
|
+
status role, locks, checks and one line per thread
|
|
1288
|
+
start --name "<name>" --goal "<sentence>" [--slug <slug>] new thread under the metadata lock: worktree,
|
|
1289
|
+
thread file, herdr panel (one start at a time)
|
|
1290
|
+
check "<name>" under the merge lock: rebase onto main, run checks, record checked
|
|
1291
|
+
merge "<name>" under the merge lock: clean main checkout, rebase, checks, --ff-only
|
|
1292
|
+
close "<name>" merged thread: close its panel, remove its worktree (branch kept)
|
|
1293
|
+
note "<name>" [--next "<text>"] [--report "<text>"] update the thread file's notes`;
|
|
1294
|
+
|
|
1295
|
+
function parseArgs(argv) {
|
|
1296
|
+
const positional = [];
|
|
1297
|
+
const options = {};
|
|
1298
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
1299
|
+
const arg = argv[i];
|
|
1300
|
+
if (arg.startsWith('--')) {
|
|
1301
|
+
if (i + 1 >= argv.length) usage(`${arg} needs a value`);
|
|
1302
|
+
options[arg.slice(2)] = argv[i + 1];
|
|
1303
|
+
i += 1;
|
|
1304
|
+
} else {
|
|
1305
|
+
positional.push(arg);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
return { positional, options };
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
const action = process.argv[2] ?? 'help';
|
|
1312
|
+
try {
|
|
1313
|
+
const { positional, options } = parseArgs(process.argv.slice(3));
|
|
1314
|
+
const actions = {
|
|
1315
|
+
help: () => HELP,
|
|
1316
|
+
claim: () => actionClaim(),
|
|
1317
|
+
status: () => actionStatus(),
|
|
1318
|
+
start: () => actionStart(options),
|
|
1319
|
+
check: () => actionCheck(positional[0]),
|
|
1320
|
+
merge: () => actionMerge(positional[0]),
|
|
1321
|
+
close: () => actionClose(positional[0]),
|
|
1322
|
+
note: () => actionNote(positional[0], options),
|
|
1323
|
+
};
|
|
1324
|
+
if (!Object.hasOwn(actions, action)) usage(`unknown action ${JSON.stringify(action)}`);
|
|
1325
|
+
const result = actions[action]();
|
|
1326
|
+
process.stdout.write(action === 'help' ? `${result}\n` : `ok ${action}: ${result}\n`);
|
|
1327
|
+
} catch (error) {
|
|
1328
|
+
releaseLocks();
|
|
1329
|
+
if (error instanceof Outcome) {
|
|
1330
|
+
const prefix = error.kind === 'copy' ? 'copy' : `${error.kind} ${action}`;
|
|
1331
|
+
process.stdout.write(`${prefix}: ${error.message}\n`);
|
|
1332
|
+
process.exitCode = EXIT[error.kind];
|
|
1333
|
+
} else {
|
|
1334
|
+
process.stdout.write(`error ${action}: ${oneLine(error.stderr?.toString() || error.message)}\n`);
|
|
1335
|
+
process.exitCode = 1;
|
|
1336
|
+
}
|
|
1337
|
+
} finally {
|
|
1338
|
+
releaseLocks();
|
|
1339
|
+
for (const note of notes) process.stdout.write(`${note}\n`);
|
|
1340
|
+
}
|