@memnexus-ai/mx-agent-cli 0.1.296-next.0 → 0.1.296-next.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/dist/__tests__/coordination-401-recovery.test.js +15 -1
- package/dist/__tests__/coordination-401-recovery.test.js.map +1 -1
- package/dist/__tests__/coordination-brief.test.js +18 -0
- package/dist/__tests__/coordination-brief.test.js.map +1 -1
- package/dist/__tests__/coordination-fallback.test.js +11 -0
- package/dist/__tests__/coordination-fallback.test.js.map +1 -1
- package/dist/__tests__/coordination-file-guards.test.d.ts +29 -0
- package/dist/__tests__/coordination-file-guards.test.d.ts.map +1 -0
- package/dist/__tests__/coordination-file-guards.test.js +380 -0
- package/dist/__tests__/coordination-file-guards.test.js.map +1 -0
- package/dist/__tests__/coordination-memory.test.js +5 -0
- package/dist/__tests__/coordination-memory.test.js.map +1 -1
- package/dist/__tests__/coordination-plain-shell-commands.test.d.ts +22 -0
- package/dist/__tests__/coordination-plain-shell-commands.test.d.ts.map +1 -0
- package/dist/__tests__/coordination-plain-shell-commands.test.js +1407 -0
- package/dist/__tests__/coordination-plain-shell-commands.test.js.map +1 -0
- package/dist/__tests__/coordination-status-plain-shell.test.d.ts +19 -0
- package/dist/__tests__/coordination-status-plain-shell.test.d.ts.map +1 -0
- package/dist/__tests__/coordination-status-plain-shell.test.js +332 -0
- package/dist/__tests__/coordination-status-plain-shell.test.js.map +1 -0
- package/dist/__tests__/coordination-token.test.js +6 -2
- package/dist/__tests__/coordination-token.test.js.map +1 -1
- package/dist/__tests__/tracked-instruction-files.test.d.ts +21 -0
- package/dist/__tests__/tracked-instruction-files.test.d.ts.map +1 -0
- package/dist/__tests__/tracked-instruction-files.test.js +489 -0
- package/dist/__tests__/tracked-instruction-files.test.js.map +1 -0
- package/dist/commands/coordination.d.ts +22 -0
- package/dist/commands/coordination.d.ts.map +1 -1
- package/dist/commands/coordination.js +168 -31
- package/dist/commands/coordination.js.map +1 -1
- package/dist/commands/create.d.ts.map +1 -1
- package/dist/commands/create.js +3 -1
- package/dist/commands/create.js.map +1 -1
- package/dist/commands/start.d.ts +28 -0
- package/dist/commands/start.d.ts.map +1 -1
- package/dist/commands/start.js +68 -4
- package/dist/commands/start.js.map +1 -1
- package/dist/lib/claude.d.ts +25 -1
- package/dist/lib/claude.d.ts.map +1 -1
- package/dist/lib/claude.js +113 -25
- package/dist/lib/claude.js.map +1 -1
- package/dist/lib/coordination-fallback.d.ts +35 -0
- package/dist/lib/coordination-fallback.d.ts.map +1 -1
- package/dist/lib/coordination-fallback.js +76 -8
- package/dist/lib/coordination-fallback.js.map +1 -1
- package/dist/lib/coordination-memory.d.ts +4 -0
- package/dist/lib/coordination-memory.d.ts.map +1 -1
- package/dist/lib/coordination-memory.js +14 -16
- package/dist/lib/coordination-memory.js.map +1 -1
- package/dist/lib/coordination-token.d.ts +8 -1
- package/dist/lib/coordination-token.d.ts.map +1 -1
- package/dist/lib/coordination-token.js +61 -15
- package/dist/lib/coordination-token.js.map +1 -1
- package/dist/lib/coordination-worktree.d.ts +286 -0
- package/dist/lib/coordination-worktree.d.ts.map +1 -0
- package/dist/lib/coordination-worktree.js +657 -0
- package/dist/lib/coordination-worktree.js.map +1 -0
- package/dist/lib/instruction-files.d.ts +30 -0
- package/dist/lib/instruction-files.d.ts.map +1 -0
- package/dist/lib/instruction-files.js +45 -0
- package/dist/lib/instruction-files.js.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,657 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* coordination-worktree -- where a team's worktree is, what may be read from it,
|
|
3
|
+
* and what to tell the operator when there is none (#507 follow-up).
|
|
4
|
+
*
|
|
5
|
+
* One rule decides the worktree root for every coordination command. Before this
|
|
6
|
+
* module the token path and `status` used `locateCoordinationWorktree` while
|
|
7
|
+
* `escalate` (`readMarkerTeam`), memory mode (`resolveMemoryTeam`) and the outage
|
|
8
|
+
* fallback file (`worktreeRoot`) each read `CLAUDE_WORKTREE_PATH` on their own,
|
|
9
|
+
* so in a plain shell `status` printed Ready and `escalate` exited 1.
|
|
10
|
+
*
|
|
11
|
+
* It is a module of its own, not part of coordination-token.ts, because
|
|
12
|
+
* coordination-token.ts imports coordination-memory.ts, and coordination-memory.ts
|
|
13
|
+
* needs the locator. coordination-token.ts re-exports the names it used to define.
|
|
14
|
+
*/
|
|
15
|
+
import { execFileSync } from 'node:child_process';
|
|
16
|
+
import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, } from 'node:fs';
|
|
17
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
18
|
+
import { findProjectRoot } from './worktree.js';
|
|
19
|
+
import { loadProjectConfig, resolveProjectConfig } from './project-config.js';
|
|
20
|
+
import { isValidProjectSlug } from './slug.js';
|
|
21
|
+
import { sanitizeField } from './coordination-render.js';
|
|
22
|
+
import { CODE_CONTEXT_FILENAME } from './code-context-file.js';
|
|
23
|
+
/** The per-worktree file naming the team this worktree reports as. */
|
|
24
|
+
export const COORDINATION_MARKER_FILE = '.mx-coordination-team';
|
|
25
|
+
/** Every per-worktree credential cache file name starts with this. */
|
|
26
|
+
export const COORDINATION_CACHE_PREFIX = '.mx-coordination-token--';
|
|
27
|
+
/** The remedy for a directory that is in no project this command can see. */
|
|
28
|
+
export const RUN_FROM_WORKTREE_REMEDY = "run this from the team's worktree (the directory holding .mx-coordination-team), or inside an mx-agent start session";
|
|
29
|
+
/** Credential variables a git child process has no use for. */
|
|
30
|
+
export const GIT_CHILD_STRIP = ['MX_COORD_SERVICE_TOKEN', 'MX_COORD_ADMIN_TOKEN', 'MX_API_KEY'];
|
|
31
|
+
/** The longest one git topology call may run. */
|
|
32
|
+
export const GIT_TOPOLOGY_TIMEOUT_MS = 5_000;
|
|
33
|
+
/**
|
|
34
|
+
* Variables that change how git reads a pathspec. `GIT_LITERAL_PATHSPECS=1` in
|
|
35
|
+
* the operator's shell turns the `:(icase)` magic and the cache glob into
|
|
36
|
+
* literal names, so a tracked cache file would not be seen (security review at
|
|
37
|
+
* 2b8c8fd, Informational 1). The child gets none of them.
|
|
38
|
+
*/
|
|
39
|
+
export const GIT_PATHSPEC_ENV = [
|
|
40
|
+
'GIT_LITERAL_PATHSPECS', 'GIT_NOGLOB_PATHSPECS', 'GIT_GLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS',
|
|
41
|
+
];
|
|
42
|
+
/**
|
|
43
|
+
* Config forced on every git call. `git ls-files` reads the index, and git runs
|
|
44
|
+
* the program named by the repository's `core.fsmonitor` when it does, so
|
|
45
|
+
* anyone who can write that repository's config would run code as the operator
|
|
46
|
+
* (security review at 2b8c8fd, Should Fix 1, CWE-829). `rev-parse` does not
|
|
47
|
+
* read the index; the override is on every call so a later one inherits it.
|
|
48
|
+
*/
|
|
49
|
+
export const GIT_CONFIG_OVERRIDES = ['-c', 'core.fsmonitor=false'];
|
|
50
|
+
/**
|
|
51
|
+
* One git call, hardened the same way for every caller in this module: an
|
|
52
|
+
* argument array (no shell), `core.fsmonitor` forced off, the coordination
|
|
53
|
+
* credentials and the pathspec switches removed from the child's environment, a
|
|
54
|
+
* timeout, and stderr discarded. Undefined when git fails, times out, or is not
|
|
55
|
+
* installed.
|
|
56
|
+
*/
|
|
57
|
+
function runGit(exec, dir, args) {
|
|
58
|
+
const env = { ...process.env };
|
|
59
|
+
for (const k of GIT_CHILD_STRIP)
|
|
60
|
+
delete env[k];
|
|
61
|
+
for (const k of GIT_PATHSPEC_ENV)
|
|
62
|
+
delete env[k];
|
|
63
|
+
try {
|
|
64
|
+
return exec('git', [...GIT_CONFIG_OVERRIDES, ...args], { cwd: dir, encoding: 'utf-8', timeout: GIT_TOPOLOGY_TIMEOUT_MS, stdio: ['ignore', 'pipe', 'ignore'], env });
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The coordination files git TRACKS at the top of the worktree `root`: the team
|
|
72
|
+
* marker and any credential cache file. An empty list means none is tracked.
|
|
73
|
+
* Undefined means git could not answer, which a caller must not read as "none".
|
|
74
|
+
*
|
|
75
|
+
* `git ls-files` with both names as pathspecs: it exits 0 and prints only the
|
|
76
|
+
* tracked matches, so "not tracked" and "git failed" cannot be confused, and
|
|
77
|
+
* one call answers for both files. It reads the index, so a file that is staged
|
|
78
|
+
* and not yet committed is in the answer.
|
|
79
|
+
*
|
|
80
|
+
* The pathspecs are `:(icase)`: git matches a pathspec case-sensitively even on
|
|
81
|
+
* a case-insensitive filesystem, where a file tracked as `.MX-Coordination-Team`
|
|
82
|
+
* is the file opened by the lower-case name (security review at 2b8c8fd, Should
|
|
83
|
+
* Fix 2, CWE-178). Names come back as git stores them; the caller lower-cases.
|
|
84
|
+
*/
|
|
85
|
+
export function defaultTrackedCoordinationFiles(root, exec = execFileSync) {
|
|
86
|
+
const out = runGit(exec, root, ['ls-files', '-z', '--', `:(icase)${COORDINATION_MARKER_FILE}`, `:(icase)${COORDINATION_CACHE_PREFIX}*`]);
|
|
87
|
+
return out === undefined ? undefined : out.split('\0').filter((f) => f !== '');
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* [toplevel, gitDir, commonDir] for `cwd`, all absolute, or undefined when git
|
|
91
|
+
* cannot answer.
|
|
92
|
+
*
|
|
93
|
+
* LAYOUT IS ASKED FOR, NOT ASSUMED, in two steps, the approach
|
|
94
|
+
* `resolveGitWritableRoots` in runtime/codex-config.ts takes:
|
|
95
|
+
*
|
|
96
|
+
* 1. `git rev-parse --path-format=absolute ...` (git >= 2.31). One call.
|
|
97
|
+
* 2. Older git has no `--path-format`: it either fails or prints the flag back
|
|
98
|
+
* as a line of output, so the answer is used only when it is exactly three
|
|
99
|
+
* absolute paths. Otherwise the top-level is asked for on its own (always
|
|
100
|
+
* absolute), then the two git dirs are asked for FROM the top-level, where a
|
|
101
|
+
* relative answer such as `.git` is relative to the top-level in every git
|
|
102
|
+
* version. Asking from a subdirectory is what older git gets wrong:
|
|
103
|
+
* `--git-common-dir` there prints `.git`, relative to the top-level, not to
|
|
104
|
+
* the directory asked from.
|
|
105
|
+
*/
|
|
106
|
+
export function defaultGitTopology(cwd, exec = execFileSync) {
|
|
107
|
+
const revParse = (dir, args) => {
|
|
108
|
+
const out = runGit(exec, dir, ['rev-parse', ...args]);
|
|
109
|
+
return out === undefined ? undefined : out.split(/\r?\n/).filter((l) => l !== '');
|
|
110
|
+
};
|
|
111
|
+
// (1) git >= 2.31.
|
|
112
|
+
const modern = revParse(cwd, ['--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir']);
|
|
113
|
+
if (modern && modern.length === 3 && modern.every((p) => isAbsolute(p)))
|
|
114
|
+
return modern;
|
|
115
|
+
// (2) older git.
|
|
116
|
+
const top = revParse(cwd, ['--show-toplevel']);
|
|
117
|
+
if (!top || top.length !== 1 || !isAbsolute(top[0]))
|
|
118
|
+
return undefined;
|
|
119
|
+
const dirs = revParse(top[0], ['--git-dir', '--git-common-dir']);
|
|
120
|
+
if (!dirs || dirs.length !== 2)
|
|
121
|
+
return undefined;
|
|
122
|
+
return [top[0], ...dirs.map((p) => resolve(top[0], p))];
|
|
123
|
+
}
|
|
124
|
+
function realOrResolved(base, p) {
|
|
125
|
+
const abs = resolve(base, p);
|
|
126
|
+
try {
|
|
127
|
+
return realpathSync(abs);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return abs;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/** The current uid, or undefined where the platform has none (Windows). */
|
|
134
|
+
function currentUid() {
|
|
135
|
+
return typeof process.getuid === 'function' ? process.getuid() : undefined;
|
|
136
|
+
}
|
|
137
|
+
/** Owner and mode of `path` itself: a link is reported, never followed. */
|
|
138
|
+
function defaultStatTop(path) {
|
|
139
|
+
try {
|
|
140
|
+
const st = lstatSync(path);
|
|
141
|
+
return { uid: st.uid, mode: st.mode };
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Rule 2c for one worktree top-level: why it may not be used, or undefined when
|
|
149
|
+
* it may. One function, so the locator and the worktree listing cannot disagree
|
|
150
|
+
* about which directories are usable. The path is passed through
|
|
151
|
+
* `sanitizeField` because the sentence is printed.
|
|
152
|
+
*
|
|
153
|
+
* Each sentence ends with a remedy that works:
|
|
154
|
+
* - mode: `chmod go-w`.
|
|
155
|
+
* - owner: CLAUDE_WORKTREE_PATH. That variable is the operator naming the team
|
|
156
|
+
* worktree, and a directory named that way is used with no owner check
|
|
157
|
+
* (rule 1), for every coordination command. A bind-mounted worktree can
|
|
158
|
+
* report another uid, and the operator is the one who knows it is theirs.
|
|
159
|
+
*
|
|
160
|
+
* THE PATH IS NEVER PRINTED AS PART OF A COMMAND (security review at 082c7d8,
|
|
161
|
+
* CWE-77). The owner refusal fires when another uid owns the directory, so that
|
|
162
|
+
* uid chose its name, and `sanitizeField` removes control bytes but keeps shell
|
|
163
|
+
* characters. The directory is named once, in prose, and the suggested command
|
|
164
|
+
* names no path.
|
|
165
|
+
*
|
|
166
|
+
* A symbolic link is reported as a link. Its lstat mode is 777, and `chmod`
|
|
167
|
+
* advice for it would be wrong. The locator never passes one: it resolves the
|
|
168
|
+
* top-level first. The worktree listing can, for an entry under `.worktrees/`.
|
|
169
|
+
*/
|
|
170
|
+
function topLevelRefusal(top, opts) {
|
|
171
|
+
const uid = (opts.uid ?? currentUid)();
|
|
172
|
+
if (uid === undefined)
|
|
173
|
+
return undefined;
|
|
174
|
+
const st = (opts.statTop ?? defaultStatTop)(top);
|
|
175
|
+
const shown = sanitizeField(top);
|
|
176
|
+
if (st && (st.mode & constants.S_IFMT) === constants.S_IFLNK) {
|
|
177
|
+
return `${shown} is a symbolic link, not a worktree directory, so it was not used; run the command from the directory it points to`;
|
|
178
|
+
}
|
|
179
|
+
if (!st || st.uid !== uid) {
|
|
180
|
+
return (`the git worktree at ${shown} is not owned by the current user, so it was not used. ` +
|
|
181
|
+
'If no other user can write to that directory (for example a bind mount that reports a different uid), ' +
|
|
182
|
+
'set CLAUDE_WORKTREE_PATH to that directory for this one command. ' +
|
|
183
|
+
'A directory named that way gets no owner check: its marker picks the team, ' +
|
|
184
|
+
'and the credential cache is read from it and written to it');
|
|
185
|
+
}
|
|
186
|
+
if ((st.mode & 0o022) !== 0) {
|
|
187
|
+
return (`the git worktree at ${shown} is group- or world-writable ` +
|
|
188
|
+
`(mode ${(st.mode & 0o777).toString(8).padStart(3, '0')}); \`chmod go-w\` on that directory makes it usable`);
|
|
189
|
+
}
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
export function locateCoordinationWorktree(env, opts = {}) {
|
|
193
|
+
const fromEnv = env.CLAUDE_WORKTREE_PATH;
|
|
194
|
+
if (fromEnv)
|
|
195
|
+
return { ok: true, root: fromEnv, source: 'CLAUDE_WORKTREE_PATH' };
|
|
196
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
197
|
+
const topo = (opts.gitTopology ?? defaultGitTopology)(cwd);
|
|
198
|
+
if (!topo) {
|
|
199
|
+
return { ok: false, reason: 'not-a-git-worktree', detail: 'CLAUDE_WORKTREE_PATH is unset and the current directory is not inside a git worktree' };
|
|
200
|
+
}
|
|
201
|
+
const [top, gitDir, commonDir] = topo.map((p) => realOrResolved(cwd, p));
|
|
202
|
+
if (gitDir === commonDir) {
|
|
203
|
+
return { ok: false, reason: 'main-checkout', top, detail: "CLAUDE_WORKTREE_PATH is unset and the current directory is the project's main checkout, not a team worktree" };
|
|
204
|
+
}
|
|
205
|
+
let projectRoot;
|
|
206
|
+
try {
|
|
207
|
+
projectRoot = realOrResolved(cwd, (opts.projectRoot ?? findProjectRoot)());
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
return { ok: false, reason: 'no-project-root', top, detail: 'CLAUDE_WORKTREE_PATH is unset and no project root could be found for the current directory' };
|
|
211
|
+
}
|
|
212
|
+
if (projectRoot !== dirname(commonDir) && projectRoot !== top) {
|
|
213
|
+
return {
|
|
214
|
+
ok: false,
|
|
215
|
+
reason: 'other-project',
|
|
216
|
+
top,
|
|
217
|
+
detail: `CLAUDE_WORKTREE_PATH is unset and the git worktree at ${sanitizeField(top)} does not belong to the project at ${sanitizeField(projectRoot)}`,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
// Rule 2c. The marker read from this directory names the team a credential is
|
|
221
|
+
// requested for, and the same directory holds the token cache, so a directory
|
|
222
|
+
// another user owns or can write must not supply either.
|
|
223
|
+
const refusal = topLevelRefusal(top, opts);
|
|
224
|
+
if (refusal) {
|
|
225
|
+
return { ok: false, reason: 'not-owned', top, detail: `CLAUDE_WORKTREE_PATH is unset and ${refusal}` };
|
|
226
|
+
}
|
|
227
|
+
return { ok: true, root: top, source: 'git-toplevel' };
|
|
228
|
+
}
|
|
229
|
+
// ── Reading a file out of the located worktree ───────────────────────────────
|
|
230
|
+
/** Largest marker or cache entry the owner-checked reader will look at. */
|
|
231
|
+
const MAX_WORKTREE_FILE_BYTES = 64 * 1024;
|
|
232
|
+
/**
|
|
233
|
+
* Read the marker or the token cache from a located worktree.
|
|
234
|
+
*
|
|
235
|
+
* `CLAUDE_WORKTREE_PATH` source: the read every caller made before this module,
|
|
236
|
+
* unchanged (missing or unreadable reads as absent).
|
|
237
|
+
*
|
|
238
|
+
* `git-toplevel` source: the file is opened with O_NOFOLLOW and O_NONBLOCK and
|
|
239
|
+
* must be a regular file owned by the current user (security review of #525). The check is
|
|
240
|
+
* made on the descriptor that is read, never on a second path lookup. The text
|
|
241
|
+
* is returned to the caller and to nothing else: no value and no length is put
|
|
242
|
+
* in a `why`.
|
|
243
|
+
*/
|
|
244
|
+
export function readWorktreeFile(located, path, opts = {}) {
|
|
245
|
+
if (located.source === 'CLAUDE_WORKTREE_PATH') {
|
|
246
|
+
try {
|
|
247
|
+
if (!existsSync(path))
|
|
248
|
+
return { kind: 'absent' };
|
|
249
|
+
return { kind: 'ok', text: readFileSync(path, 'utf-8') };
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
return { kind: 'absent' };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
lstatSync(path);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
return { kind: 'absent' };
|
|
260
|
+
}
|
|
261
|
+
let fd;
|
|
262
|
+
try {
|
|
263
|
+
// O_NONBLOCK: opening a FIFO for reading blocks until a writer appears, so
|
|
264
|
+
// without it a FIFO at the marker path hangs the command before the
|
|
265
|
+
// regular-file check below is reached (security review of #525 at eba08f4).
|
|
266
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
267
|
+
}
|
|
268
|
+
catch (err) {
|
|
269
|
+
// ELOOP is a symbolic link at the path. Every other errno is a file this
|
|
270
|
+
// run cannot open.
|
|
271
|
+
return {
|
|
272
|
+
kind: 'refused',
|
|
273
|
+
why: err.code === 'ELOOP' ? 'it is a symbolic link' : 'it could not be opened',
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
const st = fstatSync(fd);
|
|
278
|
+
if (!st.isFile())
|
|
279
|
+
return { kind: 'refused', why: 'it is not a regular file' };
|
|
280
|
+
const uid = (opts.uid ?? currentUid)();
|
|
281
|
+
if (uid !== undefined && st.uid !== uid)
|
|
282
|
+
return { kind: 'refused', why: 'it is not owned by the current user' };
|
|
283
|
+
const buffer = Buffer.alloc(Math.min(st.size, MAX_WORKTREE_FILE_BYTES));
|
|
284
|
+
const bytes = st.size === 0 ? 0 : readSync(fd, buffer, 0, buffer.length, 0);
|
|
285
|
+
return { kind: 'ok', text: buffer.subarray(0, bytes).toString('utf-8') };
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
return { kind: 'refused', why: 'it could not be read' };
|
|
289
|
+
}
|
|
290
|
+
finally {
|
|
291
|
+
closeSync(fd);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* What to do about a marker or a credential cache file that git tracks or has
|
|
296
|
+
* staged. One text for both files, printed ONCE per command output: after the
|
|
297
|
+
* reason in a refused worktree, and once under the list from the main checkout.
|
|
298
|
+
*
|
|
299
|
+
* EVERY STEP IS MEANT TO BE FOLLOWED LITERALLY, and a test does so. The text at
|
|
300
|
+
* 2b8c8fd failed that (QA M2, red-team A and C): it did not say the change is
|
|
301
|
+
* per branch, so an operator who committed it on the base branch stayed refused
|
|
302
|
+
* in every existing worktree; and it named only the marker, so the cache file
|
|
303
|
+
* `mx-agent start` stages with `git add -A` produced a second refusal.
|
|
304
|
+
*
|
|
305
|
+
* - `git ls-files` reads the INDEX of the worktree it runs in. Each worktree
|
|
306
|
+
* has its own index and its own branch, so the file has to leave the index
|
|
307
|
+
* of the refused worktree itself. A commit on another branch changes
|
|
308
|
+
* nothing there until that worktree's branch merges or rebases onto it.
|
|
309
|
+
* - A staged file is in the index, so "tracked or staged" is the true wording.
|
|
310
|
+
* - `start` takes the team slug and uses the worktree directory named
|
|
311
|
+
* `<team>` or starting with `<team>-` (`findWorktreePath`, lib/worktree.ts).
|
|
312
|
+
* It writes the marker only when the file is absent and the project config
|
|
313
|
+
* sets coordinationMode to queue (commands/start.ts step 5a), then launches
|
|
314
|
+
* the session.
|
|
315
|
+
*
|
|
316
|
+
* The commands hold constants only. No path and no file name from disk is
|
|
317
|
+
* printed inside one (security review at 082c7d8): the cache file is named by
|
|
318
|
+
* its pattern, quoted so the shell passes it to git unexpanded.
|
|
319
|
+
*/
|
|
320
|
+
export const TRACKED_REMEDY = [
|
|
321
|
+
'To fix it, do this in the refused worktree. Git tracks files per branch and every worktree has its own branch, so a change made in another worktree or on the base branch does not reach it.',
|
|
322
|
+
`1. Run \`git rm --cached -f --ignore-unmatch -- ${COORDINATION_MARKER_FILE} '${COORDINATION_CACHE_PREFIX}*'\`. It stops git tracking the marker and any credential cache file, staged or committed, on that worktree's branch. With --cached the files stay on disk, and -f lets it remove an entry whose file has changed since it was staged.`,
|
|
323
|
+
`2. Add two lines to .gitignore, \`${COORDINATION_MARKER_FILE}\` and \`${COORDINATION_CACHE_PREFIX}*\`, and commit both changes on that branch.`,
|
|
324
|
+
`3. Delete the ${COORDINATION_MARKER_FILE} file left in that worktree. It holds the value every worktree shared, not this team's.`,
|
|
325
|
+
'4. Run `mx-agent start <team>`, where <team> is the team slug: for a worktree directory named <team>-<date>, the part before the date. In a project whose mx-agent.config.json sets coordinationMode to queue, `start` writes that worktree\'s own marker because the file is absent, then opens a session. Leave the session and run this command again.',
|
|
326
|
+
'Every other worktree stays refused until its own branch stops tracking the files: repeat steps 1 to 4 there, or merge or rebase its branch onto the branch that holds the commit from step 2 and then do steps 3 and 4 there.',
|
|
327
|
+
];
|
|
328
|
+
/**
|
|
329
|
+
* Why the marker of a cwd-located worktree may not name its team, or undefined
|
|
330
|
+
* when it may (#525 red-team finding 1 at 082c7d8).
|
|
331
|
+
*
|
|
332
|
+
* A session is protected by the team `mx-agent start` asserts
|
|
333
|
+
* (MX_COORD_EXPECT_TEAM). A plain shell has no such assertion, so the
|
|
334
|
+
* `git-toplevel` source needs checks of its own, or a wrong marker requests and
|
|
335
|
+
* caches a credential for another team, which a plain shell on `origin/main`
|
|
336
|
+
* never did. Both checks FAIL CLOSED and both apply ONLY to that source. Under
|
|
337
|
+
* CLAUDE_WORKTREE_PATH nothing here runs: that path is unchanged, and fixing a
|
|
338
|
+
* wrong marker inside a session is #527.
|
|
339
|
+
*
|
|
340
|
+
* a. The marker, or a credential cache file, is tracked in git. A tracked
|
|
341
|
+
* marker is checked out by every worktree of the repository, so it names
|
|
342
|
+
* no single team (#527 defect 1: a consumer project tracked a marker
|
|
343
|
+
* holding `product`, and every team's worktree acted as `product`). When
|
|
344
|
+
* git cannot say whether it is tracked, the marker is refused too: this is
|
|
345
|
+
* the credential path, and "could not check" must not read as "checked".
|
|
346
|
+
* b. `.mx-code-context.json` in the same worktree names a different team.
|
|
347
|
+
* Provisioning writes that file per worktree. It is read with the same
|
|
348
|
+
* owner-checked, no-follow, non-blocking, size-capped reader as the marker.
|
|
349
|
+
* An absent file, an unreadable one, content that is not a JSON object, or
|
|
350
|
+
* a `team` that is missing or not a valid slug: no refusal. Three team
|
|
351
|
+
* worktrees in this repository have no such file (#433), and a file that
|
|
352
|
+
* cannot be read is not evidence of a different team.
|
|
353
|
+
*
|
|
354
|
+
* Nothing printed here can be pasted as a command with a path or a file name
|
|
355
|
+
* taken from disk: the commands name only the fixed marker file name, and a
|
|
356
|
+
* team is printed only when it is a valid slug.
|
|
357
|
+
*/
|
|
358
|
+
function cwdMarkerRefusal(located, line, opts) {
|
|
359
|
+
const shown = sanitizeField(located.root);
|
|
360
|
+
const tracked = (opts.trackedFiles ?? defaultTrackedCoordinationFiles)(located.root);
|
|
361
|
+
if (tracked === undefined) {
|
|
362
|
+
return {
|
|
363
|
+
kind: 'refused',
|
|
364
|
+
reason: 'tracked-unknown',
|
|
365
|
+
why: `git could not say whether the ${COORDINATION_MARKER_FILE} marker in ${shown} is tracked or staged, so the marker was not used`,
|
|
366
|
+
remedy: ['Run `git ls-files` in that directory to see the error.'],
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
// Lower case on both sides: the pathspecs are `:(icase)`, and on a
|
|
370
|
+
// case-insensitive filesystem a file tracked under another letter case is the
|
|
371
|
+
// file this command opens.
|
|
372
|
+
const lower = tracked.map((f) => f.toLowerCase());
|
|
373
|
+
const where = `in ${shown} is tracked or staged in git on the branch that worktree has checked out`;
|
|
374
|
+
if (lower.includes(COORDINATION_MARKER_FILE)) {
|
|
375
|
+
return {
|
|
376
|
+
kind: 'refused',
|
|
377
|
+
reason: 'tracked',
|
|
378
|
+
why: `the ${COORDINATION_MARKER_FILE} marker ${where}, so it is not that worktree's own marker and was not used`,
|
|
379
|
+
remedy: TRACKED_REMEDY,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
if (lower.some((f) => f.startsWith(COORDINATION_CACHE_PREFIX))) {
|
|
383
|
+
return {
|
|
384
|
+
kind: 'refused',
|
|
385
|
+
reason: 'tracked',
|
|
386
|
+
why: `a credential cache file (${COORDINATION_CACHE_PREFIX}*) ${where}, so the marker and the cache there were not used`,
|
|
387
|
+
remedy: TRACKED_REMEDY,
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
const team = line.replace(/\s+/g, '');
|
|
391
|
+
if (!isValidProjectSlug(team))
|
|
392
|
+
return undefined;
|
|
393
|
+
const context = readWorktreeFile(located, join(located.root, CODE_CONTEXT_FILENAME), opts);
|
|
394
|
+
if (context.kind !== 'ok')
|
|
395
|
+
return undefined;
|
|
396
|
+
let contextTeam;
|
|
397
|
+
try {
|
|
398
|
+
contextTeam = JSON.parse(context.text)?.team;
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
return undefined;
|
|
402
|
+
}
|
|
403
|
+
if (typeof contextTeam !== 'string' || !isValidProjectSlug(contextTeam) || contextTeam === team)
|
|
404
|
+
return undefined;
|
|
405
|
+
return {
|
|
406
|
+
kind: 'refused',
|
|
407
|
+
reason: 'context-mismatch',
|
|
408
|
+
why: `the ${COORDINATION_MARKER_FILE} marker in ${shown} names team "${team}" and ${CODE_CONTEXT_FILENAME} in the same worktree names team "${contextTeam}", ` +
|
|
409
|
+
'so neither was used as the team',
|
|
410
|
+
remedy: [
|
|
411
|
+
'Correct the file that is wrong. If it is the marker, delete it and run `mx-agent start <team>`, ' +
|
|
412
|
+
'which writes the marker only when the file is absent and then opens a session.',
|
|
413
|
+
],
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* The located worktree's team marker, and whether it may be used.
|
|
418
|
+
*
|
|
419
|
+
* CLAUDE_WORKTREE_PATH source: the read every caller made before this module.
|
|
420
|
+
* `git-toplevel` source: the owner-checked read, then `cwdMarkerRefusal`. Every
|
|
421
|
+
* consumer of the marker goes through here (the token path, `status`,
|
|
422
|
+
* `escalate`, memory mode, the worktree listing), so a refused marker names a
|
|
423
|
+
* team for none of them.
|
|
424
|
+
*/
|
|
425
|
+
export function readTeamMarker(located, opts = {}) {
|
|
426
|
+
const read = readWorktreeFile(located, join(located.root, COORDINATION_MARKER_FILE), opts);
|
|
427
|
+
if (read.kind === 'absent')
|
|
428
|
+
return { kind: 'absent' };
|
|
429
|
+
if (read.kind === 'refused')
|
|
430
|
+
return { kind: 'unreadable', why: read.why };
|
|
431
|
+
const line = read.text.split(/\r?\n/, 1)[0] ?? '';
|
|
432
|
+
if (located.source === 'git-toplevel') {
|
|
433
|
+
const refusal = cwdMarkerRefusal({ root: located.root, source: 'git-toplevel' }, line, opts);
|
|
434
|
+
if (refusal)
|
|
435
|
+
return refusal;
|
|
436
|
+
}
|
|
437
|
+
return { kind: 'ok', line };
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* The first line of the located worktree's team marker, untrimmed, or undefined
|
|
441
|
+
* when there is no marker this command will use. Each caller applies its own
|
|
442
|
+
* normalization, as it did before.
|
|
443
|
+
*/
|
|
444
|
+
export function readMarkerLine(located, opts = {}) {
|
|
445
|
+
const read = readTeamMarker(located, opts);
|
|
446
|
+
return read.kind === 'ok' ? read.line : undefined;
|
|
447
|
+
}
|
|
448
|
+
// ── The next step, when no marker is usable ──────────────────────────────────
|
|
449
|
+
/** Team worktrees listed in a remedy are capped, so a large project prints a bounded block. */
|
|
450
|
+
const MAX_LISTED_WORKTREES = 20;
|
|
451
|
+
/**
|
|
452
|
+
* The git worktrees under `<root>/.worktrees/`, the directory `coordination
|
|
453
|
+
* setup` scans (step 7a): those whose marker names a valid team slug, and those
|
|
454
|
+
* with no usable marker.
|
|
455
|
+
*
|
|
456
|
+
* Everything returned is printed, so everything is checked first: a team is
|
|
457
|
+
* returned only when it passes the slug rules, and a path is passed through
|
|
458
|
+
* `sanitizeField`. A marker that is a link, or is owned by another user, is not
|
|
459
|
+
* read, and its worktree counts as unmarked.
|
|
460
|
+
*
|
|
461
|
+
* A worktree the locator would refuse under rule 2c (another owner, or group-
|
|
462
|
+
* or world-writable) is in neither list: running from it would be refused, so
|
|
463
|
+
* it is never offered as the place to go. It is returned as `refused` with the
|
|
464
|
+
* locator's own sentence, and its marker is not read. So is an entry that is a
|
|
465
|
+
* symbolic link, and a worktree whose marker `readTeamMarker` refuses. Never throws.
|
|
466
|
+
*/
|
|
467
|
+
function scanTeamWorktrees(root, opts) {
|
|
468
|
+
const parent = join(root, '.worktrees');
|
|
469
|
+
const marked = [];
|
|
470
|
+
const unmarked = [];
|
|
471
|
+
const refused = [];
|
|
472
|
+
// Each distinct remedy once, however many worktrees need it.
|
|
473
|
+
const remedies = [];
|
|
474
|
+
let entries;
|
|
475
|
+
try {
|
|
476
|
+
entries = readdirSync(parent).sort();
|
|
477
|
+
}
|
|
478
|
+
catch {
|
|
479
|
+
return { marked, unmarked, refused, remedies };
|
|
480
|
+
}
|
|
481
|
+
for (const entry of entries) {
|
|
482
|
+
if (entry.startsWith('.'))
|
|
483
|
+
continue;
|
|
484
|
+
const wtPath = join(parent, entry);
|
|
485
|
+
// A git worktree has a `.git` file or directory.
|
|
486
|
+
if (!existsSync(join(wtPath, '.git')))
|
|
487
|
+
continue;
|
|
488
|
+
const refusal = topLevelRefusal(wtPath, opts);
|
|
489
|
+
if (refusal) {
|
|
490
|
+
refused.push(refusal);
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
// A marker the worktree's own commands would refuse (tracked in git, or
|
|
494
|
+
// disagreeing with its code-context file) names no team here either.
|
|
495
|
+
const read = readTeamMarker({ root: wtPath, source: 'git-toplevel' }, opts);
|
|
496
|
+
if (read.kind === 'refused') {
|
|
497
|
+
refused.push(read.why);
|
|
498
|
+
if (!remedies.some((r) => r.join('\n') === read.remedy.join('\n')))
|
|
499
|
+
remedies.push([...read.remedy]);
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
const team = (read.kind === 'ok' ? read.line : '').replace(/\s+/g, '');
|
|
503
|
+
if (isValidProjectSlug(team))
|
|
504
|
+
marked.push({ path: sanitizeField(wtPath), team });
|
|
505
|
+
else
|
|
506
|
+
unmarked.push(sanitizeField(wtPath));
|
|
507
|
+
}
|
|
508
|
+
return { marked, unmarked, refused, remedies };
|
|
509
|
+
}
|
|
510
|
+
/** Team worktrees under `<root>/.worktrees/` that hold a marker naming a valid team slug. */
|
|
511
|
+
export function listMarkedWorktrees(root, opts = {}) {
|
|
512
|
+
return scanTeamWorktrees(root, opts).marked;
|
|
513
|
+
}
|
|
514
|
+
/** A capped list of indented items, with the count of the rest. */
|
|
515
|
+
function listed(items) {
|
|
516
|
+
const shown = items.slice(0, MAX_LISTED_WORKTREES).map((i) => ` ${i}`);
|
|
517
|
+
if (items.length > shown.length)
|
|
518
|
+
shown.push(` and ${items.length - shown.length} more`);
|
|
519
|
+
return shown;
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* What `mx-agent start <team>` does about the marker for the project at `root`.
|
|
523
|
+
*
|
|
524
|
+
* `commands/start.ts` (step 5a) writes `.mx-coordination-team` into the team's
|
|
525
|
+
* worktree only when the project's mx-agent.config.json sets
|
|
526
|
+
* `coordinationMode` to `queue`. `mx-agent new project` writes that value
|
|
527
|
+
* (`commands/init.ts`), so the command works for a project it created. The
|
|
528
|
+
* config is read here so the sentence printed is true for THIS project.
|
|
529
|
+
*/
|
|
530
|
+
function startWritesMarkerLine(root) {
|
|
531
|
+
let mode;
|
|
532
|
+
if (root) {
|
|
533
|
+
try {
|
|
534
|
+
mode = resolveProjectConfig(loadProjectConfig(root)).coordinationMode;
|
|
535
|
+
}
|
|
536
|
+
catch {
|
|
537
|
+
mode = undefined;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
if (mode === 'queue') {
|
|
541
|
+
return "`mx-agent start <team>` writes the marker into that team's worktree before it launches the session.";
|
|
542
|
+
}
|
|
543
|
+
if (mode === undefined) {
|
|
544
|
+
return '`mx-agent start <team>` writes the marker into that team\'s worktree when the project\'s mx-agent.config.json sets "coordinationMode" to "queue".';
|
|
545
|
+
}
|
|
546
|
+
return ('`mx-agent start <team>` writes the marker only when mx-agent.config.json sets "coordinationMode" to "queue", ' +
|
|
547
|
+
`and the file in ${sanitizeField(root ?? '')} does not.`);
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* The lines that tell the operator what to do when no usable marker was found.
|
|
551
|
+
* The first line is a sentence; a line that starts with two spaces is a list
|
|
552
|
+
* item under the line before it.
|
|
553
|
+
*
|
|
554
|
+
* - A located worktree with no marker: the command that writes one.
|
|
555
|
+
* - The project's main checkout, or any directory whose project root is
|
|
556
|
+
* known: the team worktrees that hold a marker, by path and team. With
|
|
557
|
+
* none, that fact, the worktrees that have no marker yet, and the command
|
|
558
|
+
* that writes one.
|
|
559
|
+
* - No project in sight: run from a team worktree.
|
|
560
|
+
* - A worktree refused under rule 2c (`not-owned`): nothing. The locator's
|
|
561
|
+
* detail already ends with the remedy, and listing team worktrees would
|
|
562
|
+
* offer the directory the operator is in as the place to go. Callers print
|
|
563
|
+
* the detail; `noMarkerLines` does it for them.
|
|
564
|
+
*
|
|
565
|
+
* Never throws.
|
|
566
|
+
*/
|
|
567
|
+
export function markerNextStep(located, opts = {}) {
|
|
568
|
+
const projectRoot = () => {
|
|
569
|
+
try {
|
|
570
|
+
return (opts.projectRoot ?? findProjectRoot)();
|
|
571
|
+
}
|
|
572
|
+
catch {
|
|
573
|
+
return undefined;
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
if (located.ok)
|
|
577
|
+
return [startWritesMarkerLine(projectRoot())];
|
|
578
|
+
if (located.reason === 'not-owned')
|
|
579
|
+
return [];
|
|
580
|
+
const root = located.reason === 'main-checkout' ? located.top : projectRoot();
|
|
581
|
+
if (!root)
|
|
582
|
+
return [`Next step: ${RUN_FROM_WORKTREE_REMEDY}.`];
|
|
583
|
+
const { marked, unmarked, refused, remedies } = scanTeamWorktrees(root, opts);
|
|
584
|
+
// Worktrees the locator or the marker guard would refuse, each with its
|
|
585
|
+
// reason. Never in the lists above: a command run from one of them would be
|
|
586
|
+
// refused. A remedy shared by several of them is printed once, under the list.
|
|
587
|
+
const notUsable = refused.length > 0
|
|
588
|
+
? ['These worktrees are not usable as they are:', ...listed(refused), ...remedies.flat()]
|
|
589
|
+
: [];
|
|
590
|
+
if (marked.length > 0) {
|
|
591
|
+
return [
|
|
592
|
+
`Next step: run this command from a team worktree. These hold a ${COORDINATION_MARKER_FILE} marker:`,
|
|
593
|
+
...listed(marked.map((w) => `${w.path} (team ${w.team})`)),
|
|
594
|
+
...notUsable,
|
|
595
|
+
];
|
|
596
|
+
}
|
|
597
|
+
const where = sanitizeField(join(root, '.worktrees'));
|
|
598
|
+
const none = refused.length > 0
|
|
599
|
+
? `No usable team worktree under ${where} holds a ${COORDINATION_MARKER_FILE} marker yet.`
|
|
600
|
+
: `No team worktree under ${where} holds a ${COORDINATION_MARKER_FILE} marker yet.`;
|
|
601
|
+
if (unmarked.length > 0) {
|
|
602
|
+
return [
|
|
603
|
+
`${none} These worktrees have none:`,
|
|
604
|
+
...listed(unmarked),
|
|
605
|
+
startWritesMarkerLine(root),
|
|
606
|
+
'Then run this command again from that worktree.',
|
|
607
|
+
...notUsable,
|
|
608
|
+
];
|
|
609
|
+
}
|
|
610
|
+
if (refused.length > 0)
|
|
611
|
+
return [none, ...notUsable];
|
|
612
|
+
return [
|
|
613
|
+
none,
|
|
614
|
+
'The project has no team worktree. `mx-agent new team` creates the team-builder worktree and starts its session.',
|
|
615
|
+
startWritesMarkerLine(root),
|
|
616
|
+
'Then run this command again from that worktree.',
|
|
617
|
+
];
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* What a command prints under its own refusal when no team marker was used: the
|
|
621
|
+
* headline, then the next step.
|
|
622
|
+
*
|
|
623
|
+
* A `not-owned` refusal is NOT "no marker was found". The directory may hold
|
|
624
|
+
* one; it was not read because the directory itself was refused. That case
|
|
625
|
+
* prints the locator's detail, which names the mode or the owner and the
|
|
626
|
+
* remedy, and nothing else (#525 red-team N1, QA M1 and M2).
|
|
627
|
+
*/
|
|
628
|
+
export function noMarkerLines(located, opts = {}) {
|
|
629
|
+
if (!located.ok && located.reason === 'not-owned')
|
|
630
|
+
return [`${located.detail}.`];
|
|
631
|
+
if (located.ok) {
|
|
632
|
+
// A marker that is there and was not used is not "no marker" either.
|
|
633
|
+
const read = readTeamMarker(located, opts);
|
|
634
|
+
if (read.kind === 'refused')
|
|
635
|
+
return [`${read.why.charAt(0).toUpperCase()}${read.why.slice(1)}.`, ...read.remedy];
|
|
636
|
+
if (read.kind === 'unreadable') {
|
|
637
|
+
return [`The ${COORDINATION_MARKER_FILE} marker in ${sanitizeField(located.root)} was not read: ${read.why}.`];
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
return ['No team marker was found.', ...markerNextStep(located, opts)];
|
|
641
|
+
}
|
|
642
|
+
/** `markerNextStep` as one line, for a detail string printed on a single stderr line. */
|
|
643
|
+
export function markerNextStepInline(located, opts = {}) {
|
|
644
|
+
const out = [];
|
|
645
|
+
for (const line of markerNextStep(located, opts)) {
|
|
646
|
+
// A list item joins the sentence before it; items are separated by a semicolon.
|
|
647
|
+
if (line.startsWith(' ') && out.length > 0) {
|
|
648
|
+
const prev = out[out.length - 1];
|
|
649
|
+
out[out.length - 1] = `${prev}${prev.endsWith(':') ? ' ' : '; '}${line.trim()}`;
|
|
650
|
+
}
|
|
651
|
+
else {
|
|
652
|
+
out.push(line);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
return out.join(' ');
|
|
656
|
+
}
|
|
657
|
+
//# sourceMappingURL=coordination-worktree.js.map
|