@memnexus-ai/mx-agent-cli 0.1.295-next.0 → 0.1.296-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/__tests__/claude-local-sanitizer.test.d.ts +24 -0
  2. package/dist/__tests__/claude-local-sanitizer.test.d.ts.map +1 -0
  3. package/dist/__tests__/claude-local-sanitizer.test.js +906 -0
  4. package/dist/__tests__/claude-local-sanitizer.test.js.map +1 -0
  5. package/dist/__tests__/coordination-401-recovery.test.js +15 -1
  6. package/dist/__tests__/coordination-401-recovery.test.js.map +1 -1
  7. package/dist/__tests__/coordination-brief.test.js +18 -0
  8. package/dist/__tests__/coordination-brief.test.js.map +1 -1
  9. package/dist/__tests__/coordination-client.test.js +90 -1
  10. package/dist/__tests__/coordination-client.test.js.map +1 -1
  11. package/dist/__tests__/coordination-credential-endpoint.test.js +90 -30
  12. package/dist/__tests__/coordination-credential-endpoint.test.js.map +1 -1
  13. package/dist/__tests__/coordination-fallback.test.js +11 -0
  14. package/dist/__tests__/coordination-fallback.test.js.map +1 -1
  15. package/dist/__tests__/coordination-file-guards.test.d.ts +29 -0
  16. package/dist/__tests__/coordination-file-guards.test.d.ts.map +1 -0
  17. package/dist/__tests__/coordination-file-guards.test.js +380 -0
  18. package/dist/__tests__/coordination-file-guards.test.js.map +1 -0
  19. package/dist/__tests__/coordination-memory.test.js +5 -0
  20. package/dist/__tests__/coordination-memory.test.js.map +1 -1
  21. package/dist/__tests__/coordination-plain-shell-commands.test.d.ts +22 -0
  22. package/dist/__tests__/coordination-plain-shell-commands.test.d.ts.map +1 -0
  23. package/dist/__tests__/coordination-plain-shell-commands.test.js +1407 -0
  24. package/dist/__tests__/coordination-plain-shell-commands.test.js.map +1 -0
  25. package/dist/__tests__/coordination-status-plain-shell.test.d.ts +19 -0
  26. package/dist/__tests__/coordination-status-plain-shell.test.d.ts.map +1 -0
  27. package/dist/__tests__/coordination-status-plain-shell.test.js +332 -0
  28. package/dist/__tests__/coordination-status-plain-shell.test.js.map +1 -0
  29. package/dist/__tests__/coordination-status-registration.test.js +8 -8
  30. package/dist/__tests__/coordination-status-registration.test.js.map +1 -1
  31. package/dist/__tests__/coordination-token-multitenant.test.js +14 -14
  32. package/dist/__tests__/coordination-token-multitenant.test.js.map +1 -1
  33. package/dist/__tests__/coordination-token.test.js +6 -2
  34. package/dist/__tests__/coordination-token.test.js.map +1 -1
  35. package/dist/__tests__/provision-completion-rows.test.js +96 -4
  36. package/dist/__tests__/provision-completion-rows.test.js.map +1 -1
  37. package/dist/__tests__/row15-detail-sanitizer.test.d.ts +20 -0
  38. package/dist/__tests__/row15-detail-sanitizer.test.d.ts.map +1 -0
  39. package/dist/__tests__/row15-detail-sanitizer.test.js +61 -0
  40. package/dist/__tests__/row15-detail-sanitizer.test.js.map +1 -0
  41. package/dist/commands/coordination.d.ts +22 -0
  42. package/dist/commands/coordination.d.ts.map +1 -1
  43. package/dist/commands/coordination.js +173 -31
  44. package/dist/commands/coordination.js.map +1 -1
  45. package/dist/commands/create.d.ts +9 -0
  46. package/dist/commands/create.d.ts.map +1 -1
  47. package/dist/commands/create.js +98 -43
  48. package/dist/commands/create.js.map +1 -1
  49. package/dist/commands/start.d.ts.map +1 -1
  50. package/dist/commands/start.js +6 -0
  51. package/dist/commands/start.js.map +1 -1
  52. package/dist/lib/behavioral-injection.d.ts +9 -0
  53. package/dist/lib/behavioral-injection.d.ts.map +1 -1
  54. package/dist/lib/behavioral-injection.js +10 -1
  55. package/dist/lib/behavioral-injection.js.map +1 -1
  56. package/dist/lib/claude.d.ts +48 -0
  57. package/dist/lib/claude.d.ts.map +1 -1
  58. package/dist/lib/claude.js +172 -22
  59. package/dist/lib/claude.js.map +1 -1
  60. package/dist/lib/coordination-client.d.ts +29 -1
  61. package/dist/lib/coordination-client.d.ts.map +1 -1
  62. package/dist/lib/coordination-client.js +52 -0
  63. package/dist/lib/coordination-client.js.map +1 -1
  64. package/dist/lib/coordination-fallback.d.ts +35 -0
  65. package/dist/lib/coordination-fallback.d.ts.map +1 -1
  66. package/dist/lib/coordination-fallback.js +76 -8
  67. package/dist/lib/coordination-fallback.js.map +1 -1
  68. package/dist/lib/coordination-memory.d.ts +4 -0
  69. package/dist/lib/coordination-memory.d.ts.map +1 -1
  70. package/dist/lib/coordination-memory.js +14 -16
  71. package/dist/lib/coordination-memory.js.map +1 -1
  72. package/dist/lib/coordination-token.d.ts +50 -14
  73. package/dist/lib/coordination-token.d.ts.map +1 -1
  74. package/dist/lib/coordination-token.js +113 -43
  75. package/dist/lib/coordination-token.js.map +1 -1
  76. package/dist/lib/coordination-worktree.d.ts +286 -0
  77. package/dist/lib/coordination-worktree.d.ts.map +1 -0
  78. package/dist/lib/coordination-worktree.js +657 -0
  79. package/dist/lib/coordination-worktree.js.map +1 -0
  80. package/dist/lib/roster.d.ts +13 -1
  81. package/dist/lib/roster.d.ts.map +1 -1
  82. package/dist/lib/roster.js +7 -3
  83. package/dist/lib/roster.js.map +1 -1
  84. package/dist/lib/roster.test.js +4 -4
  85. package/dist/lib/roster.test.js.map +1 -1
  86. package/dist/lib/team-identity.js +2 -2
  87. package/dist/lib/team-identity.js.map +1 -1
  88. package/package.json +1 -1
@@ -0,0 +1,1407 @@
1
+ /**
2
+ * #507 follow-up, fix round on PR #525 -- every coordination command in a plain
3
+ * shell, and what a refusal tells the operator.
4
+ *
5
+ * The red-team challenge on #525 (comment 5951655534) and the security review
6
+ * (comment 5934585482) found, at e809e09:
7
+ *
8
+ * F2. `status` found the team from the git worktree of the current directory,
9
+ * while `escalate`, memory mode and the outage fallback file still read
10
+ * only CLAUDE_WORKTREE_PATH. `status` printed Ready and `escalate` exited 1.
11
+ * F1. The refusal said "run this from the team's worktree" and named no
12
+ * worktree and no command that creates a marker.
13
+ * F3. The git topology call needed git 2.31 (`--path-format=absolute`).
14
+ * Security. The cwd-located worktree was trusted with no owner check; `status`
15
+ * printed raw marker bytes; nothing pinned the git child's stripped
16
+ * environment or its timeout.
17
+ *
18
+ * Every fixture is a real git repository under the OS temp dir. The operator's
19
+ * global config is mocked out, and every token and key here is a fake literal.
20
+ */
21
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
22
+ import { chmodSync, existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync, realpathSync, } from 'fs';
23
+ import { execFileSync, spawnSync } from 'child_process';
24
+ import { join } from 'path';
25
+ import { tmpdir } from 'os';
26
+ vi.mock('../lib/config.js', async (importOriginal) => {
27
+ const actual = await importOriginal();
28
+ return {
29
+ ...actual,
30
+ getConfigValue: () => undefined,
31
+ loadConfig: () => ({}),
32
+ getConfigPath: () => '/nonexistent-mx-agent-config-for-525/config.json',
33
+ };
34
+ });
35
+ import { runEscalate, runStatus } from '../commands/coordination.js';
36
+ import { runInit } from '../commands/init.js';
37
+ import { ENV_KEY_USER_KEY, refreshCoordinationToken, resolveCoordinationToken } from '../lib/coordination-token.js';
38
+ import { registrationLine } from '../commands/coordination.js';
39
+ import { sanitizeField } from '../lib/coordination-render.js';
40
+ import { GIT_CHILD_STRIP, GIT_TOPOLOGY_TIMEOUT_MS, defaultGitTopology, listMarkedWorktrees, locateCoordinationWorktree, markerNextStep, GIT_PATHSPEC_ENV, TRACKED_REMEDY, defaultTrackedCoordinationFiles, noMarkerLines, readTeamMarker, readWorktreeFile, } from '../lib/coordination-worktree.js';
41
+ import { resolveMemoryTeam } from '../lib/coordination-memory.js';
42
+ import { FALLBACK_FILENAME, worktreeRoot } from '../lib/coordination-fallback.js';
43
+ import { ServiceUnreachableError, resetUrlFallbackWarning } from '../lib/coordination-client.js';
44
+ const ENV_KEYS = [
45
+ 'CLAUDE_WORKTREE_PATH', 'CLAUDE_WORKTREE_NAME', 'MX_PROJECT_ROOT', 'MX_PRODUCT_SLUG',
46
+ 'MX_COORD_SERVICE_URL', 'MX_COORD_SERVICE_TOKEN', 'MX_COORD_ADMIN_TOKEN', 'MX_API_KEY',
47
+ 'MX_COORDINATION_MODE', 'MX_COORD_EXPECT_TEAM', 'MX_COORD_EXPECT_PROJECT',
48
+ 'GIT_LITERAL_PATHSPECS', 'GIT_NOGLOB_PATHSPECS', 'GIT_GLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS',
49
+ ];
50
+ let base;
51
+ let saved;
52
+ let logs;
53
+ let errs;
54
+ function git(cwd, ...a) {
55
+ const r = spawnSync('git', ['-c', 'user.email=t@e.com', '-c', 'user.name=t', ...a], { cwd, encoding: 'utf-8' });
56
+ if (r.status !== 0)
57
+ throw new Error(r.stderr);
58
+ }
59
+ /**
60
+ * A project as `mx-agent new project` leaves it: a main checkout whose
61
+ * mx-agent.config.json names `slug` and sets coordinationMode to queue, and
62
+ * linked worktrees under `<main>/.worktrees/`.
63
+ */
64
+ function makeProject(name, slug, worktrees = ['alpha-20260101'], mode = 'queue') {
65
+ const main = join(base, name);
66
+ mkdirSync(main, { recursive: true });
67
+ git(main, 'init', '-q', '-b', 'main');
68
+ writeFileSync(join(main, 'mx-agent.config.json'), JSON.stringify({ projectSlug: slug, ...(mode ? { coordinationMode: mode } : {}) }));
69
+ writeFileSync(join(main, '.gitignore'), '.worktrees/\n.mx-coordination-team\n');
70
+ git(main, 'add', '-A');
71
+ git(main, 'commit', '-q', '-m', 'init');
72
+ const paths = worktrees.map((wt) => {
73
+ const p = join(main, '.worktrees', wt);
74
+ git(main, 'worktree', 'add', '-q', '-b', `worktree/${wt}`, p);
75
+ // Pinned, not inherited: the locator refuses a group-writable worktree, and
76
+ // under umask 0002 `git worktree add` makes one (#525 red-team N2).
77
+ chmodSync(p, 0o755);
78
+ return p;
79
+ });
80
+ return { main, worktrees: paths, worktree: paths[0] };
81
+ }
82
+ /** A queue client that accepts everything and records what was enqueued. */
83
+ function recordingClient(enqueue) {
84
+ return {
85
+ enqueue,
86
+ async drain() { return { messages: [], remaining: 0, batchId: '' }; },
87
+ async confirmDrain() { },
88
+ async ack() { },
89
+ async history() { return { messages: [], nextBefore: '' }; },
90
+ async respondToMessage() { return { messageId: '', obligationState: 'resolved', stateNote: null, stateChangedAt: '' }; },
91
+ async getObligations() { return { owe: [], owed: [] }; },
92
+ };
93
+ }
94
+ const noOffline = {
95
+ readOriginRoster: () => ({ teams: null, source: 'origin/main', error: 'no ref in this test' }),
96
+ readFileRoster: (p) => ({ teams: null, source: p, error: 'no file in this test' }),
97
+ };
98
+ function credentialDeps(fetchCredential) {
99
+ return {
100
+ project: 'life-planner',
101
+ serviceUrl: 'https://mxagent.dev.memnexus.ai',
102
+ readUserKey: () => 'test-user-key-not-real',
103
+ fetchCredential,
104
+ writeCache: () => true,
105
+ };
106
+ }
107
+ const issued = () => vi.fn(async () => ({ status: 'issued', token: 'tok' }));
108
+ /** Put the process in a plain shell at `dir`: no session variables, cwd there. */
109
+ function plainShellAt(dir) {
110
+ vi.spyOn(process, 'cwd').mockReturnValue(dir);
111
+ }
112
+ beforeEach(() => {
113
+ base = realpathSync(mkdtempSync(join(tmpdir(), 'coord-525-plain-')));
114
+ saved = {};
115
+ for (const k of ENV_KEYS) {
116
+ saved[k] = process.env[k];
117
+ delete process.env[k];
118
+ }
119
+ process.env.MX_COORDINATION_MODE = 'queue';
120
+ logs = [];
121
+ errs = [];
122
+ vi.spyOn(console, 'log').mockImplementation((m) => { logs.push(String(m)); });
123
+ vi.spyOn(console, 'error').mockImplementation((m) => { errs.push(String(m)); });
124
+ vi.spyOn(process.stderr, 'write').mockImplementation((() => true));
125
+ vi.spyOn(process, 'exit').mockImplementation(((code) => { throw new Error(`process.exit(${code})`); }));
126
+ resetUrlFallbackWarning();
127
+ });
128
+ afterEach(() => {
129
+ vi.restoreAllMocks();
130
+ for (const k of ENV_KEYS) {
131
+ if (saved[k] === undefined)
132
+ delete process.env[k];
133
+ else
134
+ process.env[k] = saved[k];
135
+ }
136
+ rmSync(base, { recursive: true, force: true });
137
+ });
138
+ // ── F2. Every command finds the team the same way ───────────────────────
139
+ describe('F2: escalate, memory mode and the fallback file in a plain shell', () => {
140
+ it('escalate sends from the marker team with no CLAUDE_WORKTREE_PATH and no --team', async () => {
141
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
142
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
143
+ process.env.MX_PROJECT_ROOT = main;
144
+ plainShellAt(worktree);
145
+ const enqueue = vi.fn(async () => ({ messageId: 'm1', duplicate: false }));
146
+ await runEscalate({ to: 'beta', priority: 'p2', body: 'hello' }, { client: recordingClient(enqueue) });
147
+ expect(process.exit).not.toHaveBeenCalled();
148
+ expect(enqueue).toHaveBeenCalledTimes(1);
149
+ expect(enqueue).toHaveBeenCalledWith(expect.objectContaining({ to: 'beta', from: 'alpha' }));
150
+ expect(logs.join('\n')).toContain('escalated: m1 -> beta [p2]');
151
+ });
152
+ it('escalate from a subdirectory of the worktree finds the same team', async () => {
153
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
154
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
155
+ const sub = join(worktree, 'src', 'deep');
156
+ mkdirSync(sub, { recursive: true });
157
+ process.env.MX_PROJECT_ROOT = main;
158
+ plainShellAt(sub);
159
+ const enqueue = vi.fn(async () => ({ messageId: 'm2', duplicate: false }));
160
+ await runEscalate({ to: 'beta', priority: 'p1', body: 'hello' }, { client: recordingClient(enqueue) });
161
+ expect(enqueue).toHaveBeenCalledWith(expect.objectContaining({ from: 'alpha' }));
162
+ });
163
+ it('an explicit --team still wins over the marker', async () => {
164
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
165
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
166
+ process.env.MX_PROJECT_ROOT = main;
167
+ plainShellAt(worktree);
168
+ const enqueue = vi.fn(async () => ({ messageId: 'm3', duplicate: false }));
169
+ await runEscalate({ to: 'beta', priority: 'p2', body: 'hello', team: 'gamma' }, { client: recordingClient(enqueue) });
170
+ expect(enqueue).toHaveBeenCalledWith(expect.objectContaining({ from: 'gamma' }));
171
+ });
172
+ it('CLAUDE_WORKTREE_PATH still means that path only', async () => {
173
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
174
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
175
+ const session = join(base, 'session');
176
+ mkdirSync(session);
177
+ writeFileSync(join(session, '.mx-coordination-team'), 'beta\n');
178
+ process.env.MX_PROJECT_ROOT = main;
179
+ process.env.CLAUDE_WORKTREE_PATH = session;
180
+ plainShellAt(worktree);
181
+ const enqueue = vi.fn(async () => ({ messageId: 'm4', duplicate: false }));
182
+ await runEscalate({ to: 'gamma', priority: 'p2', body: 'hello' }, { client: recordingClient(enqueue) });
183
+ expect(enqueue).toHaveBeenCalledWith(expect.objectContaining({ from: 'beta' }));
184
+ expect(resolveMemoryTeam()).toBe('beta');
185
+ expect(worktreeRoot()).toBe(session);
186
+ });
187
+ it('memory mode resolves the same team from the marker', () => {
188
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
189
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
190
+ process.env.MX_PROJECT_ROOT = main;
191
+ plainShellAt(worktree);
192
+ expect(resolveMemoryTeam()).toBe('alpha');
193
+ expect(resolveMemoryTeam('gamma')).toBe('gamma');
194
+ });
195
+ it('on an outage the fallback entry is written at the worktree top, not in the subdirectory', async () => {
196
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
197
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
198
+ const sub = join(worktree, 'src');
199
+ mkdirSync(sub);
200
+ process.env.MX_PROJECT_ROOT = main;
201
+ plainShellAt(sub);
202
+ const enqueue = vi.fn(async () => { throw new ServiceUnreachableError(new Error('down')); });
203
+ await runEscalate({ to: 'beta', priority: 'p2', body: 'hello' }, { client: recordingClient(enqueue) });
204
+ expect(logs.join('\n')).toContain('queued locally, will flush on reconnect');
205
+ expect(existsSync(join(worktree, FALLBACK_FILENAME))).toBe(true);
206
+ expect(existsSync(join(sub, FALLBACK_FILENAME))).toBe(false);
207
+ const entry = JSON.parse(readFileSync(join(worktree, FALLBACK_FILENAME), 'utf-8').trim());
208
+ expect(entry).toMatchObject({ from: 'alpha', to: 'beta' });
209
+ });
210
+ it('where the locator refuses (the main checkout), the fallback root is still the current directory', () => {
211
+ const { main } = makeProject('life-planner', 'life-planner');
212
+ process.env.MX_PROJECT_ROOT = main;
213
+ plainShellAt(main);
214
+ expect(worktreeRoot()).toBe(main);
215
+ });
216
+ it('escalate with no team anywhere exits 1 and names the team worktrees it can see', async () => {
217
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
218
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
219
+ process.env.MX_PROJECT_ROOT = main;
220
+ plainShellAt(main);
221
+ const enqueue = vi.fn(async () => ({ messageId: 'never', duplicate: false }));
222
+ await expect(runEscalate({ to: 'beta', priority: 'p2', body: 'hello' }, { client: recordingClient(enqueue) }))
223
+ .rejects.toThrow('process.exit(1)');
224
+ expect(enqueue).not.toHaveBeenCalled();
225
+ const out = errs.join('\n');
226
+ expect(out).toContain('could not determine your team');
227
+ expect(out).toContain(`${worktree} (team alpha)`);
228
+ });
229
+ });
230
+ // ── F1. The refusal names a next step that works ────────────────────────
231
+ describe('F1: the next step when no marker is usable', () => {
232
+ const unprovisioned = { resolveToken: async () => ({ status: 'unprovisioned', detail: 'test' }), ...noOffline };
233
+ const okFetch = () => vi.fn(async (_url) => new Response('ok', { status: 200 }));
234
+ it('status from the main checkout lists the team worktrees that hold a marker, by path and team', async () => {
235
+ const { main, worktrees } = makeProject('life-planner', 'life-planner', ['alpha-20260101', 'beta-20260101', 'gamma-20260101']);
236
+ writeFileSync(join(worktrees[0], '.mx-coordination-team'), 'alpha\n');
237
+ writeFileSync(join(worktrees[1], '.mx-coordination-team'), 'beta\n');
238
+ process.env.MX_PROJECT_ROOT = main;
239
+ await runStatus({ fetch: okFetch(), locate: { cwd: main }, registration: unprovisioned });
240
+ const out = logs.join('\n');
241
+ expect(out).toContain('Team: not set');
242
+ expect(out).toContain('Next step: run this command from a team worktree. These hold a .mx-coordination-team marker:');
243
+ expect(out).toContain(` ${worktrees[0]} (team alpha)`);
244
+ expect(out).toContain(` ${worktrees[1]} (team beta)`);
245
+ // The third worktree has no marker, so it is not offered.
246
+ expect(out).not.toContain(worktrees[2]);
247
+ });
248
+ it('status from the main checkout with no marked worktree says so, lists the unmarked ones, and names the command that writes a marker', async () => {
249
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
250
+ process.env.MX_PROJECT_ROOT = main;
251
+ await runStatus({ fetch: okFetch(), locate: { cwd: main }, registration: unprovisioned });
252
+ const out = logs.join('\n');
253
+ expect(out).toContain(`No team worktree under ${join(main, '.worktrees')} holds a .mx-coordination-team marker yet. These worktrees have none:`);
254
+ expect(out).toContain(` ${worktree}\n`);
255
+ expect(out).toContain("`mx-agent start <team>` writes the marker into that team's worktree before it launches the session.");
256
+ expect(out).not.toContain('mx-agent new team');
257
+ });
258
+ it('status from the main checkout of a project with no team worktree names the command that creates one', async () => {
259
+ const { main } = makeProject('life-planner', 'life-planner', []);
260
+ process.env.MX_PROJECT_ROOT = main;
261
+ await runStatus({ fetch: okFetch(), locate: { cwd: main }, registration: unprovisioned });
262
+ const out = logs.join('\n');
263
+ expect(out).toContain(`No team worktree under ${join(main, '.worktrees')} holds a .mx-coordination-team marker yet.`);
264
+ expect(out).toContain('The project has no team worktree. `mx-agent new team` creates the team-builder worktree and starts its session.');
265
+ expect(out).toContain("`mx-agent start <team>` writes the marker into that team's worktree before it launches the session.");
266
+ });
267
+ it('status from a linked worktree with no marker names the command that writes it', async () => {
268
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
269
+ process.env.MX_PROJECT_ROOT = main;
270
+ await runStatus({ fetch: okFetch(), locate: { cwd: worktree }, registration: unprovisioned });
271
+ const out = logs.join('\n');
272
+ expect(out).toContain('No team marker was found.');
273
+ expect(out).toContain("`mx-agent start <team>` writes the marker into that team's worktree before it launches the session.");
274
+ expect(out).not.toContain('run this command from a team worktree');
275
+ });
276
+ it('the token path gives the same next step from a linked worktree with no marker', async () => {
277
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
278
+ const fetchCredential = issued();
279
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate: { cwd: worktree, projectRoot: () => main } });
280
+ expect(res.status).toBe('unprovisioned');
281
+ expect(res.detail).toContain('no coordination marker (.mx-coordination-team) in this worktree');
282
+ expect(res.detail).toContain('`mx-agent start <team>` writes the marker into that team\'s worktree');
283
+ expect(fetchCredential).not.toHaveBeenCalled();
284
+ });
285
+ it('a project whose config is not in queue mode is told the start command will not write the marker', () => {
286
+ const { main, worktree } = makeProject('other', 'other', ['alpha-20260101'], '');
287
+ const located = locateCoordinationWorktree({}, { cwd: worktree, projectRoot: () => main });
288
+ const lines = markerNextStep(located, { projectRoot: () => main });
289
+ expect(lines.join('\n')).toContain('writes the marker only when mx-agent.config.json sets "coordinationMode" to "queue"');
290
+ expect(lines.join('\n')).toContain(`and the file in ${main} does not.`);
291
+ });
292
+ it('the start remedy is true for a project `mx-agent new project` scaffolds: init writes coordinationMode queue', async () => {
293
+ const root = join(base, 'scaffolded');
294
+ mkdirSync(root);
295
+ await runInit({ projectRoot: root, projectSlug: 'proj9', skipBootstrap: true });
296
+ expect(JSON.parse(readFileSync(join(root, 'mx-agent.config.json'), 'utf-8')).coordinationMode).toBe('queue');
297
+ const lines = markerNextStep({ ok: false, reason: 'main-checkout', top: root, detail: '' }, { projectRoot: () => root });
298
+ expect(lines).toContain("`mx-agent start <team>` writes the marker into that team's worktree before it launches the session.");
299
+ });
300
+ it('outside any project the next step is the general one', () => {
301
+ const noProject = () => { throw new Error('no project'); };
302
+ const located = locateCoordinationWorktree({}, { gitTopology: () => undefined, projectRoot: noProject });
303
+ expect(markerNextStep(located, { projectRoot: noProject })).toEqual([
304
+ "Next step: run this from the team's worktree (the directory holding .mx-coordination-team), or inside an mx-agent start session.",
305
+ ]);
306
+ });
307
+ it('a marker that does not hold a valid slug is never listed, and its bytes are never printed', () => {
308
+ const { main, worktrees } = makeProject('life-planner', 'life-planner', ['alpha-20260101', 'evil-20260101']);
309
+ writeFileSync(join(worktrees[0], '.mx-coordination-team'), 'alpha\n');
310
+ writeFileSync(join(worktrees[1], '.mx-coordination-team'), 'te\x1b[31mRED\x1b[0mam\x1b]0;TITLE\x07\n');
311
+ expect(listMarkedWorktrees(main)).toEqual([{ path: worktrees[0], team: 'alpha' }]);
312
+ const text = markerNextStep({ ok: false, reason: 'main-checkout', top: main, detail: '' }).join('\n');
313
+ expect(text).not.toContain('\x1b');
314
+ expect(text).not.toContain('RED');
315
+ });
316
+ it('a marker that is a symbolic link is not followed when worktrees are listed', () => {
317
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
318
+ const target = join(base, 'elsewhere');
319
+ writeFileSync(target, 'alpha\n');
320
+ symlinkSync(target, join(worktree, '.mx-coordination-team'));
321
+ expect(listMarkedWorktrees(main)).toEqual([]);
322
+ });
323
+ });
324
+ // ── The product owner's run, reproduced ─────────────────────────────────
325
+ /**
326
+ * His output, on 0.1.296-next.0, from `/workspace (main)` in Life Planner: a
327
+ * credential-endpoint project in queue mode, run from the MAIN CHECKOUT with no
328
+ * CLAUDE_WORKTREE_PATH and no global config. It printed `Team: not set`, then
329
+ * said a roster "does not list this team", that "the team name came from the
330
+ * worktree name", and recommended `coordination brief` and `coordination
331
+ * setup`. No team was resolved, so the first two described a lookup that had no
332
+ * subject, `brief` cannot run without a team, and `setup` needs an admin token
333
+ * a credential-endpoint project never has.
334
+ *
335
+ * Nothing is injected below except the health ping: the token path, the
336
+ * locator and the project root all run as they do in his shell.
337
+ */
338
+ describe('the Life Planner run: main checkout, credential-endpoint project, queue mode, plain shell', () => {
339
+ /**
340
+ * Every mx-agent command the output names. The words are the CLI's real
341
+ * subcommands, so "the built-in mx-agent service URL" is not counted as one.
342
+ */
343
+ function commandsNamed(out) {
344
+ return [...new Set(out.match(/mx-agent (?:coordination [a-z]+|new [a-z]+|start|provision|escalate|init|config)/g) ?? [])].sort();
345
+ }
346
+ async function runFromMainCheckout(main) {
347
+ delete process.env.MX_COORDINATION_MODE; // the mode comes from mx-agent.config.json, as in his project
348
+ plainShellAt(main);
349
+ const fetchFn = vi.fn(async (_url) => new Response('ok', { status: 200 }));
350
+ await runStatus({ fetch: fetchFn });
351
+ expect(fetchFn).toHaveBeenCalledTimes(1);
352
+ return logs.join('\n');
353
+ }
354
+ function expectNoFalseClaim(out) {
355
+ expect(out).toContain('Project: life-planner');
356
+ expect(out).toContain('Team: not set');
357
+ expect(out).toContain('Coordination mode: queue');
358
+ expect(out).toContain('Service URL: https://mxagent.dev.memnexus.ai (source: the built-in mx-agent service URL (nothing configured))');
359
+ expect(out).toContain('Registered: unverified (source: no roster consulted: no team was resolved)');
360
+ expect(out).toContain("? Could not verify — no team was resolved: CLAUDE_WORKTREE_PATH is unset and the current directory is the project's main checkout, not a team worktree");
361
+ // No claim about a team that was never resolved.
362
+ expect(out).not.toContain('does not list this team');
363
+ expect(out).not.toContain('lists this team');
364
+ expect(out).not.toContain('came from the worktree name');
365
+ expect(out).not.toContain('The queue may hold this team');
366
+ // No step that cannot work here.
367
+ expect(out).not.toContain('coordination setup');
368
+ expect(out).not.toContain('coordination brief');
369
+ expect(out).not.toContain('MX_COORD_ADMIN_TOKEN');
370
+ }
371
+ it('with team worktrees that hold markers: lists them, and names no step that cannot work', async () => {
372
+ const { main, worktrees } = makeProject('life-planner', 'life-planner', ['planner-20260925', 'team-builder-20260925']);
373
+ writeFileSync(join(worktrees[0], '.mx-coordination-team'), 'planner\n');
374
+ writeFileSync(join(worktrees[1], '.mx-coordination-team'), 'team-builder\n');
375
+ const out = await runFromMainCheckout(main);
376
+ expectNoFalseClaim(out);
377
+ expect(out).toContain('Next step: run this command from a team worktree. These hold a .mx-coordination-team marker:');
378
+ expect(out).toContain(` ${worktrees[0]} (team planner)`);
379
+ expect(out).toContain(` ${worktrees[1]} (team team-builder)`);
380
+ expect(commandsNamed(out)).toEqual([]);
381
+ });
382
+ it('with team worktrees but no marker: lists them and names the command that writes the marker', async () => {
383
+ const { main, worktrees } = makeProject('life-planner', 'life-planner', ['planner-20260925', 'team-builder-20260925']);
384
+ const out = await runFromMainCheckout(main);
385
+ expectNoFalseClaim(out);
386
+ expect(out).toContain('holds a .mx-coordination-team marker yet. These worktrees have none:');
387
+ expect(out).toContain(` ${worktrees[0]}\n`);
388
+ expect(out).toContain(` ${worktrees[1]}\n`);
389
+ expect(out).toContain("`mx-agent start <team>` writes the marker into that team's worktree before it launches the session.");
390
+ expect(out).toContain('Then run this command again from that worktree.');
391
+ expect(commandsNamed(out)).toEqual(['mx-agent start']);
392
+ });
393
+ it('with no team worktree at all: names the command that creates one', async () => {
394
+ const { main } = makeProject('life-planner', 'life-planner', []);
395
+ const out = await runFromMainCheckout(main);
396
+ expectNoFalseClaim(out);
397
+ expect(commandsNamed(out)).toEqual(['mx-agent new team', 'mx-agent start']);
398
+ });
399
+ it('a credential-endpoint project with a team resolved is not sent to `coordination setup`', async () => {
400
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
401
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
402
+ process.env.MX_PROJECT_ROOT = main;
403
+ await runStatus({
404
+ fetch: vi.fn(async (_url) => new Response('ok', { status: 200 })),
405
+ locate: { cwd: worktree },
406
+ registration: { resolveToken: async () => ({ status: 'unprovisioned', detail: 'no MemNexus user key is available on this machine' }), ...noOffline },
407
+ });
408
+ const out = logs.join('\n');
409
+ expect(out).toContain('? Could not verify');
410
+ expect(out).toContain('mx-agent coordination brief');
411
+ expect(out).not.toContain('mx-agent coordination setup ');
412
+ expect(out).toContain('This project needs no `coordination setup`');
413
+ });
414
+ it('a Key Vault project with a team resolved still names `coordination setup`', async () => {
415
+ const { main, worktree } = makeProject('memnexus', 'memnexus', ['platform-20260101']);
416
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'platform\n');
417
+ process.env.MX_PROJECT_ROOT = main;
418
+ await runStatus({
419
+ locate: { cwd: worktree },
420
+ registration: { resolveToken: async () => ({ status: 'unprovisioned', detail: 'test' }), ...noOffline },
421
+ });
422
+ expect(logs.join('\n')).toContain('mx-agent coordination setup # registers the team if it is absent');
423
+ });
424
+ });
425
+ // ── F3. git older than 2.31 ─────────────────────────────────────────────
426
+ describe('F3: a git with no --path-format still locates a real worktree', () => {
427
+ const real = execFileSync;
428
+ /** git < 2.31 as a failure: the first call errors. */
429
+ const failingFirstCall = (file, args, options) => {
430
+ if (args.includes('--path-format=absolute'))
431
+ throw new Error('unknown option: --path-format=absolute');
432
+ return real(file, args, options);
433
+ };
434
+ /** git < 2.31 as it behaves: rev-parse prints the unknown flag back as a line. */
435
+ const echoingFirstCall = (file, args, options) => {
436
+ if (!args.includes('--path-format=absolute'))
437
+ return real(file, args, options);
438
+ return `--path-format=absolute\n${real(file, args.filter((a) => a !== '--path-format=absolute'), options)}`;
439
+ };
440
+ for (const [label, exec] of [['fails', failingFirstCall], ['echoes the flag', echoingFirstCall]]) {
441
+ it(`first call ${label}: a linked worktree is located from its top-level and from a subdirectory`, () => {
442
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
443
+ const sub = join(worktree, 'src', 'deep');
444
+ mkdirSync(sub, { recursive: true });
445
+ const gitTopology = (cwd) => defaultGitTopology(cwd, exec);
446
+ expect(locateCoordinationWorktree({}, { cwd: worktree, projectRoot: () => main, gitTopology }))
447
+ .toEqual({ ok: true, root: worktree, source: 'git-toplevel' });
448
+ expect(locateCoordinationWorktree({}, { cwd: sub, projectRoot: () => main, gitTopology }))
449
+ .toEqual({ ok: true, root: worktree, source: 'git-toplevel' });
450
+ });
451
+ it(`first call ${label}: the main checkout is still refused, from its top-level and from a subdirectory`, () => {
452
+ const { main } = makeProject('life-planner', 'life-planner');
453
+ const sub = join(main, 'docs');
454
+ mkdirSync(sub);
455
+ const gitTopology = (cwd) => defaultGitTopology(cwd, exec);
456
+ for (const cwd of [main, sub]) {
457
+ const r = locateCoordinationWorktree({}, { cwd, projectRoot: () => main, gitTopology });
458
+ expect(r.ok).toBe(false);
459
+ if (!r.ok)
460
+ expect(r.reason).toBe('main-checkout');
461
+ }
462
+ });
463
+ }
464
+ it('the fallback answer equals the one-call answer on this git', () => {
465
+ const { worktree } = makeProject('life-planner', 'life-planner');
466
+ const modern = defaultGitTopology(worktree)?.map((p) => realpathSync(p));
467
+ const old = defaultGitTopology(worktree, failingFirstCall)?.map((p) => realpathSync(p));
468
+ expect(modern).toHaveLength(3);
469
+ expect(old).toEqual(modern);
470
+ });
471
+ it('a directory outside any repository is still undefined on both paths', () => {
472
+ const plain = join(base, 'not-a-repo');
473
+ mkdirSync(plain);
474
+ expect(defaultGitTopology(plain)).toBeUndefined();
475
+ expect(defaultGitTopology(plain, failingFirstCall)).toBeUndefined();
476
+ });
477
+ });
478
+ // ── Security review of #525 ─────────────────────────────────────────────
479
+ describe.skipIf(typeof process.getuid !== 'function')('security: the cwd-located worktree must be owned by the current user', () => {
480
+ const uid = () => process.getuid();
481
+ it("a top-level another user owns is refused, and no credential is requested", async () => {
482
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
483
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'forgedother\n');
484
+ const locate = { cwd: worktree, projectRoot: () => main, statTop: () => ({ uid: uid() + 1, mode: 0o40755 }) };
485
+ const r = locateCoordinationWorktree({}, locate);
486
+ expect(r.ok).toBe(false);
487
+ if (!r.ok) {
488
+ expect(r.reason).toBe('not-owned');
489
+ expect(r.detail).toContain('is not owned by the current user');
490
+ }
491
+ const fetchCredential = issued();
492
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate });
493
+ expect(res.status).toBe('unprovisioned');
494
+ expect(fetchCredential).not.toHaveBeenCalled();
495
+ });
496
+ it('a group-writable top-level is refused with its mode, and no credential is requested', async () => {
497
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
498
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
499
+ chmodSync(worktree, 0o775);
500
+ const locate = { cwd: worktree, projectRoot: () => main };
501
+ const r = locateCoordinationWorktree({}, locate);
502
+ expect(r.ok).toBe(false);
503
+ if (!r.ok)
504
+ expect(r.detail).toContain('is group- or world-writable (mode 775)');
505
+ const fetchCredential = issued();
506
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate });
507
+ expect(res.status).toBe('unprovisioned');
508
+ expect(fetchCredential).not.toHaveBeenCalled();
509
+ });
510
+ it('a world-writable top-level is refused', () => {
511
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
512
+ chmodSync(worktree, 0o757);
513
+ const r = locateCoordinationWorktree({}, { cwd: worktree, projectRoot: () => main });
514
+ expect(r.ok).toBe(false);
515
+ });
516
+ it('a 0755 top-level the current user owns is accepted (the layout `git worktree add` makes under umask 022)', () => {
517
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
518
+ chmodSync(worktree, 0o755);
519
+ expect(locateCoordinationWorktree({}, { cwd: worktree, projectRoot: () => main }))
520
+ .toEqual({ ok: true, root: worktree, source: 'git-toplevel' });
521
+ });
522
+ it('CLAUDE_WORKTREE_PATH is not subject to the owner rule: behaviour there is unchanged', () => {
523
+ const r = locateCoordinationWorktree({ CLAUDE_WORKTREE_PATH: '/some/session/worktree' }, { statTop: () => ({ uid: uid() + 1, mode: 0o40777 }) });
524
+ expect(r).toEqual({ ok: true, root: '/some/session/worktree', source: 'CLAUDE_WORKTREE_PATH' });
525
+ });
526
+ it('a marker that is a symbolic link is not read on the git-toplevel source, and no credential is requested', async () => {
527
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
528
+ const target = join(base, 'planted-marker');
529
+ writeFileSync(target, 'forgedother\n');
530
+ symlinkSync(target, join(worktree, '.mx-coordination-team'));
531
+ const fetchCredential = issued();
532
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate: { cwd: worktree, projectRoot: () => main } });
533
+ expect(res.status).toBe('unprovisioned');
534
+ expect(res.detail).toContain('was not read: it is a symbolic link');
535
+ expect(fetchCredential).not.toHaveBeenCalled();
536
+ });
537
+ it('a marker another user owns is not read on the git-toplevel source, and no credential is requested', async () => {
538
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
539
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'forgedother\n');
540
+ // The directory passes (stubbed), so the refusal below is the FILE check:
541
+ // the marker's real owner is not the uid this run claims to be.
542
+ const other = uid() + 1;
543
+ const locate = { cwd: worktree, projectRoot: () => main, uid: () => other, statTop: () => ({ uid: other, mode: 0o40755 }) };
544
+ expect(locateCoordinationWorktree({}, locate).ok).toBe(true);
545
+ const fetchCredential = issued();
546
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate });
547
+ expect(res.status).toBe('unprovisioned');
548
+ expect(res.detail).toContain('was not read: it is not owned by the current user');
549
+ expect(fetchCredential).not.toHaveBeenCalled();
550
+ });
551
+ it('a credential cache that is a symbolic link is not used as the token on the git-toplevel source', async () => {
552
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
553
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
554
+ const target = join(base, 'planted-cache');
555
+ writeFileSync(target, 'planted-token-not-real\n');
556
+ symlinkSync(target, join(worktree, '.mx-coordination-token--life-planner--alpha'));
557
+ const fetchCredential = issued();
558
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate: { cwd: worktree, projectRoot: () => main } });
559
+ expect(res.status).toBe('resolved');
560
+ expect(res.source).toBe('credential');
561
+ expect(res.token).toBe('tok');
562
+ expect(fetchCredential).toHaveBeenCalledTimes(1);
563
+ });
564
+ it('a regular cache file the current user owns is still used, and no request is made', async () => {
565
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
566
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
567
+ writeFileSync(join(worktree, '.mx-coordination-token--life-planner--alpha'), 'cached-token-not-real\n', { mode: 0o600 });
568
+ const fetchCredential = issued();
569
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate: { cwd: worktree, projectRoot: () => main } });
570
+ expect(res.status).toBe('resolved');
571
+ expect(res.source).toBe('cache');
572
+ expect(fetchCredential).not.toHaveBeenCalled();
573
+ });
574
+ });
575
+ describe('security: status never prints raw marker bytes (Informational 1)', () => {
576
+ const okFetch = () => vi.fn(async (_url) => new Response('ok', { status: 200 }));
577
+ it('a marker holding escape sequences prints as "invalid marker"', async () => {
578
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
579
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'te\x1b[31mRED\x1b[0mam\x1b]0;TITLE\x07\n');
580
+ process.env.MX_PROJECT_ROOT = main;
581
+ await runStatus({
582
+ fetch: okFetch(),
583
+ locate: { cwd: worktree },
584
+ registration: { resolveToken: async () => ({ status: 'unprovisioned', detail: 'test' }), ...noOffline },
585
+ });
586
+ const out = logs.join('\n');
587
+ expect(out).toContain('Team: invalid marker\n');
588
+ expect(out).not.toContain('\x1b');
589
+ expect(out).not.toContain('\x07');
590
+ expect(out).not.toContain('RED');
591
+ expect(out).toContain('does not hold a valid team slug');
592
+ });
593
+ it('a marker holding a valid slug still prints the slug', async () => {
594
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
595
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
596
+ process.env.MX_PROJECT_ROOT = main;
597
+ await runStatus({
598
+ fetch: okFetch(),
599
+ locate: { cwd: worktree },
600
+ registration: { resolveToken: async () => ({ status: 'unprovisioned', detail: 'test' }), ...noOffline },
601
+ });
602
+ expect(logs.join('\n')).toContain('Team: alpha (marker in');
603
+ });
604
+ });
605
+ describe('security: the git child process (Informational 2)', () => {
606
+ function capture(answer) {
607
+ const calls = [];
608
+ return { calls, exec: (file, args, options) => { calls.push({ file, args, options }); return answer(args); } };
609
+ }
610
+ beforeEach(() => {
611
+ process.env.MX_COORD_SERVICE_TOKEN = 'fake-service-token';
612
+ process.env.MX_COORD_ADMIN_TOKEN = 'fake-admin-token';
613
+ process.env.MX_API_KEY = 'fake-user-key';
614
+ });
615
+ it('the strip list names the three credential variables', () => {
616
+ expect([...GIT_CHILD_STRIP].sort()).toEqual(['MX_API_KEY', 'MX_COORD_ADMIN_TOKEN', 'MX_COORD_SERVICE_TOKEN']);
617
+ expect(GIT_CHILD_STRIP).toContain(ENV_KEY_USER_KEY);
618
+ });
619
+ it('runs git with an argument array, a 5 s timeout, and none of the three credentials in its environment', () => {
620
+ const { exec, calls } = capture(() => '/p/.worktrees/a\n/p/.git/worktrees/a\n/p/.git\n');
621
+ expect(defaultGitTopology('/p/.worktrees/a', exec)).toEqual(['/p/.worktrees/a', '/p/.git/worktrees/a', '/p/.git']);
622
+ expect(calls).toHaveLength(1);
623
+ const { file, args, options } = calls[0];
624
+ expect(file).toBe('git');
625
+ expect(args).toEqual(['-c', 'core.fsmonitor=false', 'rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir']);
626
+ expect(GIT_TOPOLOGY_TIMEOUT_MS).toBe(5_000);
627
+ expect(options.timeout).toBe(5_000);
628
+ expect(options.cwd).toBe('/p/.worktrees/a');
629
+ expect(options).not.toHaveProperty('shell');
630
+ for (const k of ['MX_COORD_SERVICE_TOKEN', 'MX_COORD_ADMIN_TOKEN', 'MX_API_KEY']) {
631
+ expect(options.env).not.toHaveProperty(k);
632
+ }
633
+ // The rest of the environment is passed through: git needs PATH and HOME.
634
+ expect(options.env.PATH).toBe(process.env.PATH);
635
+ // The parent's own environment is untouched.
636
+ expect(process.env.MX_API_KEY).toBe('fake-user-key');
637
+ });
638
+ it('every call on the older-git path has the same timeout and the same stripped environment', () => {
639
+ const { exec, calls } = capture((args) => {
640
+ if (args.includes('--path-format=absolute'))
641
+ throw new Error('unknown option');
642
+ return args.includes('--show-toplevel') ? '/p/.worktrees/a\n' : '/p/.git/worktrees/a\n/p/.git\n';
643
+ });
644
+ expect(defaultGitTopology('/p/.worktrees/a/src', exec)).toEqual(['/p/.worktrees/a', '/p/.git/worktrees/a', '/p/.git']);
645
+ expect(calls).toHaveLength(3);
646
+ // The two git dirs are asked for from the top-level, not from the subdirectory.
647
+ expect(calls[2].options.cwd).toBe('/p/.worktrees/a');
648
+ for (const c of calls) {
649
+ expect(c.options.timeout).toBe(5_000);
650
+ for (const k of ['MX_COORD_SERVICE_TOKEN', 'MX_COORD_ADMIN_TOKEN', 'MX_API_KEY']) {
651
+ expect(c.options.env).not.toHaveProperty(k);
652
+ }
653
+ }
654
+ });
655
+ it('a relative answer on the older-git path is resolved against the top-level', () => {
656
+ const { exec } = capture((args) => {
657
+ if (args.includes('--path-format=absolute'))
658
+ throw new Error('unknown option');
659
+ return args.includes('--show-toplevel') ? '/p\n' : '.git\n.git\n';
660
+ });
661
+ expect(defaultGitTopology('/p/docs', exec)).toEqual(['/p', '/p/.git', '/p/.git']);
662
+ });
663
+ });
664
+ // ── Fix round 3: reviews at eba08f4 ─────────────────────────────────────
665
+ /**
666
+ * For hand-made entries, which are not git worktrees: git cannot say what is
667
+ * tracked there, so the answer is given (nothing is tracked).
668
+ */
669
+ const NOT_TRACKED = { trackedFiles: () => [] };
670
+ /** A hand-made entry under `<main>/.worktrees/`: a directory with a `.git` file, mode 0755. */
671
+ function fakeWorktree(main, name, marker) {
672
+ const p = join(main, '.worktrees', name);
673
+ mkdirSync(p, { recursive: true });
674
+ chmodSync(p, 0o755);
675
+ writeFileSync(join(p, '.git'), 'gitdir: /nowhere\n');
676
+ if (marker !== undefined)
677
+ writeFileSync(join(p, '.mx-coordination-team'), marker);
678
+ return p;
679
+ }
680
+ describe.skipIf(typeof process.getuid !== 'function')('N1: a worktree the locator refused is reported as refused, by every command', () => {
681
+ const unprovisioned = { resolveToken: async () => ({ status: 'unprovisioned', detail: 'test' }), ...noOffline };
682
+ const okFetch = () => vi.fn(async (_url) => new Response('ok', { status: 200 }));
683
+ const CHMOD = 'is group- or world-writable (mode 775); `chmod go-w` on that directory makes it usable';
684
+ function expectNoContradiction(out, worktree) {
685
+ expect(out).toContain(CHMOD);
686
+ expect(out).not.toContain('No team marker was found');
687
+ expect(out).not.toContain('this directory names none');
688
+ expect(out).not.toContain('run this command from a team worktree');
689
+ expect(out).not.toContain(`${worktree} (team`);
690
+ }
691
+ it('status from a group-writable worktree prints the chmod remedy and does not send the operator back to it', async () => {
692
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
693
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
694
+ chmodSync(worktree, 0o775);
695
+ process.env.MX_PROJECT_ROOT = main;
696
+ await runStatus({ fetch: okFetch(), locate: { cwd: worktree }, registration: unprovisioned });
697
+ const out = logs.join('\n');
698
+ expectNoContradiction(out, worktree);
699
+ expect(out).toContain('No team was looked up, because the worktree of this directory was not used.');
700
+ });
701
+ it('escalate from a group-writable worktree exits 1 with the chmod remedy and no worktree list', async () => {
702
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
703
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
704
+ chmodSync(worktree, 0o775);
705
+ process.env.MX_PROJECT_ROOT = main;
706
+ plainShellAt(worktree);
707
+ const enqueue = vi.fn(async () => ({ messageId: 'never', duplicate: false }));
708
+ await expect(runEscalate({ to: 'beta', priority: 'p2', body: 'hello' }, { client: recordingClient(enqueue) }))
709
+ .rejects.toThrow('process.exit(1)');
710
+ expect(enqueue).not.toHaveBeenCalled();
711
+ expectNoContradiction(errs.join('\n'), worktree);
712
+ });
713
+ it('the token path detail for a group-writable worktree ends with the chmod remedy and lists nothing', async () => {
714
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
715
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
716
+ chmodSync(worktree, 0o775);
717
+ const fetchCredential = issued();
718
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate: { cwd: worktree, projectRoot: () => main } });
719
+ expect(res.status).toBe('unprovisioned');
720
+ expectNoContradiction(res.detail ?? '', worktree);
721
+ expect(res.detail).toMatch(/cannot locate the coordination marker$/);
722
+ expect(fetchCredential).not.toHaveBeenCalled();
723
+ });
724
+ it('noMarkerLines for a refused worktree is the locator detail and nothing else', () => {
725
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
726
+ chmodSync(worktree, 0o775);
727
+ const located = locateCoordinationWorktree({}, { cwd: worktree, projectRoot: () => main });
728
+ expect(located.ok).toBe(false);
729
+ if (!located.ok)
730
+ expect(noMarkerLines(located, { projectRoot: () => main })).toEqual([`${located.detail}.`]);
731
+ expect(markerNextStep(located, { projectRoot: () => main })).toEqual([]);
732
+ });
733
+ it('from the main checkout a group-writable worktree is not offered as a place to go: it is listed as not usable, with the remedy', async () => {
734
+ const { main, worktrees } = makeProject('life-planner', 'life-planner', ['alpha-20260101', 'beta-20260101']);
735
+ writeFileSync(join(worktrees[0], '.mx-coordination-team'), 'alpha\n');
736
+ writeFileSync(join(worktrees[1], '.mx-coordination-team'), 'beta\n');
737
+ chmodSync(worktrees[1], 0o775);
738
+ process.env.MX_PROJECT_ROOT = main;
739
+ await runStatus({ fetch: okFetch(), locate: { cwd: main }, registration: unprovisioned });
740
+ const out = logs.join('\n');
741
+ expect(out).toContain(` ${worktrees[0]} (team alpha)`);
742
+ expect(out).not.toContain('(team beta)');
743
+ expect(out).toContain('These worktrees are not usable as they are:');
744
+ expect(out).toContain(` the git worktree at ${worktrees[1]} ${CHMOD}`);
745
+ expect(listMarkedWorktrees(main)).toEqual([{ path: worktrees[0], team: 'alpha' }]);
746
+ });
747
+ it('from the main checkout with only a refused worktree: no worktree is called usable', () => {
748
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
749
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
750
+ chmodSync(worktree, 0o775);
751
+ const lines = markerNextStep({ ok: false, reason: 'main-checkout', top: main, detail: '' }, { projectRoot: () => main });
752
+ expect(lines).toEqual([
753
+ `No usable team worktree under ${join(main, '.worktrees')} holds a .mx-coordination-team marker yet.`,
754
+ 'These worktrees are not usable as they are:',
755
+ ` the git worktree at ${worktree} ${CHMOD}`,
756
+ ]);
757
+ });
758
+ it("a worktree another user owns is not offered either, and its marker is not read", () => {
759
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
760
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
761
+ const other = process.getuid() + 1;
762
+ const lines = markerNextStep({ ok: false, reason: 'main-checkout', top: main, detail: '' }, { projectRoot: () => main, statTop: () => ({ uid: other, mode: 0o40755 }) });
763
+ expect(lines.join('\n')).not.toContain('(team alpha)');
764
+ expect(lines.join('\n')).toContain(`the git worktree at ${worktree} is not owned by the current user`);
765
+ });
766
+ });
767
+ describe.skipIf(typeof process.getuid !== 'function')('N3: the not-owned refusal names a remedy, and the remedy works for every command that prints it', () => {
768
+ const realUid = () => process.getuid();
769
+ it('the detail names CLAUDE_WORKTREE_PATH with the directory, and says what setting it means', () => {
770
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
771
+ const r = locateCoordinationWorktree({}, { cwd: worktree, projectRoot: () => main, statTop: () => ({ uid: realUid() + 1, mode: 0o40755 }) });
772
+ expect(r.ok).toBe(false);
773
+ if (!r.ok) {
774
+ expect(r.detail).toBe(`CLAUDE_WORKTREE_PATH is unset and the git worktree at ${worktree} is not owned by the current user, so it was not used. ` +
775
+ 'If no other user can write to that directory (for example a bind mount that reports a different uid), ' +
776
+ 'set CLAUDE_WORKTREE_PATH to that directory for this one command. ' +
777
+ 'A directory named that way gets no owner check: its marker picks the team, ' +
778
+ 'and the credential cache is read from it and written to it');
779
+ // The directory is named once, in prose. Another uid chose its name, so
780
+ // it is never printed after the `=` of an assignment an operator could paste.
781
+ expect(r.detail).not.toContain('CLAUDE_WORKTREE_PATH=');
782
+ expect(r.detail.split(worktree)).toHaveLength(2);
783
+ }
784
+ });
785
+ it('with the directory reading as another uid, every command refuses in a plain shell and works with CLAUDE_WORKTREE_PATH set', async () => {
786
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
787
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
788
+ process.env.MX_PROJECT_ROOT = main;
789
+ plainShellAt(worktree);
790
+ // A bind mount that reports another owner: this process is a uid the
791
+ // directory and its files do not belong to.
792
+ const other = realUid() + 1;
793
+ vi.spyOn(process, 'getuid').mockReturnValue(other);
794
+ // Refused, and each refusal carries the remedy.
795
+ expect(resolveMemoryTeam()).not.toBe('alpha');
796
+ const refusedFetch = issued();
797
+ const refused = await resolveCoordinationToken({ ...credentialDeps(refusedFetch) });
798
+ expect(refused.status).toBe('unprovisioned');
799
+ expect(refused.detail).toContain('set CLAUDE_WORKTREE_PATH to that directory for this one command');
800
+ expect(refusedFetch).not.toHaveBeenCalled();
801
+ const never = vi.fn(async () => ({ messageId: 'never', duplicate: false }));
802
+ await expect(runEscalate({ to: 'beta', priority: 'p2', body: 'hello' }, { client: recordingClient(never) }))
803
+ .rejects.toThrow('process.exit(1)');
804
+ expect(errs.join('\n')).toContain('set CLAUDE_WORKTREE_PATH to that directory for this one command');
805
+ // The remedy, followed.
806
+ process.env.CLAUDE_WORKTREE_PATH = worktree;
807
+ expect(locateCoordinationWorktree(process.env)).toEqual({ ok: true, root: worktree, source: 'CLAUDE_WORKTREE_PATH' });
808
+ expect(resolveMemoryTeam()).toBe('alpha');
809
+ expect(worktreeRoot()).toBe(worktree);
810
+ const enqueue = vi.fn(async () => ({ messageId: 'm9', duplicate: false }));
811
+ await runEscalate({ to: 'beta', priority: 'p2', body: 'hello' }, { client: recordingClient(enqueue) });
812
+ expect(enqueue).toHaveBeenCalledWith(expect.objectContaining({ from: 'alpha' }));
813
+ const fetchCredential = issued();
814
+ const res = await resolveCoordinationToken({ ...credentialDeps(fetchCredential) });
815
+ expect(res.status).toBe('resolved');
816
+ expect(res.slug).toBe('alpha');
817
+ logs.length = 0;
818
+ await runStatus({
819
+ fetch: vi.fn(async (_url) => new Response('ok', { status: 200 })),
820
+ registration: { client: recordingClient(enqueue), ...noOffline },
821
+ });
822
+ expect(logs.join('\n')).toMatch(/Team: {14}alpha\n/);
823
+ expect(logs.join('\n')).toContain('✓ Ready');
824
+ });
825
+ });
826
+ describe('security Informational 1: a worktree path is printed only through sanitizeField', () => {
827
+ it('status in a worktree whose name holds escape sequences prints none of them on the Team or Registered line', async () => {
828
+ const { main } = makeProject('life-planner', 'life-planner', []);
829
+ // The directory name holds the escape sequences; the branch name cannot.
830
+ const worktree = join(main, '.worktrees', 'te\x1b[31mam\x1b]0;TITLE\x07');
831
+ git(main, 'worktree', 'add', '-q', '-b', 'worktree/esc', worktree);
832
+ chmodSync(worktree, 0o755);
833
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
834
+ process.env.MX_PROJECT_ROOT = main;
835
+ await runStatus({
836
+ fetch: vi.fn(async (_url) => new Response('ok', { status: 200 })),
837
+ locate: { cwd: worktree },
838
+ registration: {
839
+ resolveToken: async () => ({ status: 'unprovisioned', detail: 'test' }),
840
+ readOriginRoster: () => ({ teams: null, source: 'origin/main', error: 'no ref in this test' }),
841
+ },
842
+ });
843
+ const team = logs.find((l) => l.includes('Team:')) ?? '';
844
+ const registered = logs.find((l) => l.includes('Registered:')) ?? '';
845
+ expect(team).toContain('Team: alpha (marker in ');
846
+ expect(team).toContain(`(marker in ${sanitizeField(worktree)}, the git worktree of the current directory)`);
847
+ expect(registered).toContain('coordination-rosters.generated.json');
848
+ for (const line of [team, registered]) {
849
+ expect(line).not.toContain('\x1b');
850
+ expect(line).not.toContain('\x07');
851
+ }
852
+ });
853
+ it('registrationLine strips control bytes from any source it is given', () => {
854
+ const line = registrationLine({ verdict: 'could-not-verify', kind: 'offline-file', source: 'offline roster from /p/te\x1b[31mam/x.json', credentialResolved: false });
855
+ expect(line).toBe('unverified (source: offline roster from /p/team/x.json)');
856
+ expect(sanitizeField('/p/te\x1b[31mam/x.json')).toBe('/p/team/x.json');
857
+ });
858
+ });
859
+ describe('security mutants that survived at eba08f4', () => {
860
+ const ESC_NAME = 'te\x1b[31mam\x1b]0;TITLE\x07';
861
+ it('M08: a listed MARKED worktree path holds no control bytes', () => {
862
+ const { main } = makeProject('life-planner', 'life-planner', []);
863
+ fakeWorktree(main, ESC_NAME, 'alpha\n');
864
+ const marked = listMarkedWorktrees(main, NOT_TRACKED);
865
+ expect(marked).toEqual([{ path: sanitizeField(join(main, '.worktrees', ESC_NAME)), team: 'alpha' }]);
866
+ expect(marked[0].path).not.toContain('\x1b');
867
+ expect(marked[0].path).not.toContain('\x07');
868
+ });
869
+ it('M08b: a listed UNMARKED worktree path holds no control bytes', () => {
870
+ const { main } = makeProject('life-planner', 'life-planner', []);
871
+ fakeWorktree(main, ESC_NAME);
872
+ const text = markerNextStep({ ok: false, reason: 'main-checkout', top: main, detail: '' }, { projectRoot: () => main }).join('\n');
873
+ expect(text).toContain(` ${sanitizeField(join(main, '.worktrees', ESC_NAME))}\n`);
874
+ expect(text).not.toContain('\x1b');
875
+ expect(text).not.toContain('\x07');
876
+ });
877
+ it('M09: more than 20 worktrees print 20 and a count of the rest, marked and unmarked', () => {
878
+ const { main } = makeProject('life-planner', 'life-planner', []);
879
+ for (let i = 0; i < 25; i++)
880
+ fakeWorktree(main, `team${String(i).padStart(2, '0')}-20260101`, `team${String(i).padStart(2, '0')}\n`);
881
+ const marked = markerNextStep({ ok: false, reason: 'main-checkout', top: main, detail: '' }, { projectRoot: () => main, ...NOT_TRACKED });
882
+ expect(marked.filter((l) => l.includes('(team team'))).toHaveLength(20);
883
+ expect(marked[marked.length - 1]).toBe(' and 5 more');
884
+ expect(marked).toHaveLength(22);
885
+ const other = makeProject('other-planner', 'other-planner', []);
886
+ for (let i = 0; i < 23; i++)
887
+ fakeWorktree(other.main, `wt${String(i).padStart(2, '0')}`);
888
+ const unmarked = markerNextStep({ ok: false, reason: 'main-checkout', top: other.main, detail: '' }, { projectRoot: () => other.main });
889
+ expect(unmarked.filter((l) => l.startsWith(` ${other.main}`))).toHaveLength(20);
890
+ expect(unmarked).toContain(' and 3 more');
891
+ });
892
+ it('M17: a marker or cache larger than 64 KB is read up to 64 KB and no further', () => {
893
+ const { worktree } = makeProject('life-planner', 'life-planner');
894
+ const path = join(worktree, '.mx-coordination-team');
895
+ writeFileSync(path, `alpha\n${'x'.repeat(200 * 1024)}`);
896
+ const read = readWorktreeFile({ root: worktree, source: 'git-toplevel' }, path);
897
+ expect(read.kind).toBe('ok');
898
+ if (read.kind === 'ok')
899
+ expect(read.text).toHaveLength(64 * 1024);
900
+ });
901
+ it.skipIf(typeof process.getuid !== 'function')('M19: the not-owned detail holds no control bytes from the path, for the owner and the mode refusal', () => {
902
+ const uid = process.getuid();
903
+ const top = `/p/.worktrees/${ESC_NAME}`;
904
+ const gitTopology = () => [top, '/p/.git/worktrees/x', '/p/.git'];
905
+ for (const st of [{ uid: uid + 1, mode: 0o40755 }, { uid, mode: 0o40775 }]) {
906
+ const r = locateCoordinationWorktree({}, { cwd: '/p', gitTopology, projectRoot: () => '/p', statTop: () => st });
907
+ expect(r.ok).toBe(false);
908
+ if (!r.ok) {
909
+ expect(r.reason).toBe('not-owned');
910
+ expect(r.detail).toContain(sanitizeField(top));
911
+ expect(r.detail).not.toContain('\x1b');
912
+ expect(r.detail).not.toContain('\x07');
913
+ }
914
+ }
915
+ });
916
+ });
917
+ // ── Fix round 4: reviews at 082c7d8 ─────────────────────────────────────
918
+ /**
919
+ * The red-team's fixture, and the layout #527 reports for a real consumer
920
+ * project: `.mx-coordination-team` holding `product` is COMMITTED on main, so
921
+ * every worktree checks it out.
922
+ */
923
+ function makeTrackedMarkerProject() {
924
+ const main = join(base, 'life-planner');
925
+ mkdirSync(main, { recursive: true });
926
+ git(main, 'init', '-q', '-b', 'main');
927
+ writeFileSync(join(main, 'mx-agent.config.json'), JSON.stringify({ projectSlug: 'life-planner', coordinationMode: 'queue' }));
928
+ writeFileSync(join(main, '.gitignore'), '.worktrees/\n.mx-coordination-token--*\n');
929
+ writeFileSync(join(main, '.mx-coordination-team'), 'product\n');
930
+ git(main, 'add', '-A');
931
+ git(main, 'add', '-f', '.mx-coordination-team');
932
+ git(main, 'commit', '-q', '-m', 'init with a tracked marker');
933
+ const worktrees = ['personal-coach-20260927', 'engineering-20260927'].map((wt) => {
934
+ const p = join(main, '.worktrees', wt);
935
+ git(main, 'worktree', 'add', '-q', '-b', `worktree/${wt}`, p);
936
+ chmodSync(p, 0o755);
937
+ return p;
938
+ });
939
+ return { main, worktrees };
940
+ }
941
+ const cacheFilesIn = (dir) => readdirSync(dir).filter((f) => f.startsWith('.mx-coordination-token--'));
942
+ /** The token path as a plain shell runs it: real locator, real cache writer, fake credential fetch. */
943
+ function plainShellTokenDeps(fetchCredential) {
944
+ return {
945
+ project: 'life-planner',
946
+ serviceUrl: 'https://mxagent.dev.memnexus.ai',
947
+ readUserKey: () => 'test-user-key-not-real',
948
+ fetchCredential,
949
+ };
950
+ }
951
+ describe('red-team finding 1: a cwd-located marker that is tracked in git names no team', () => {
952
+ const okFetch = () => vi.fn(async (_url) => new Response('ok', { status: 200 }));
953
+ it('each worktree checks out the tracked marker (the fixture is the one the finding used)', () => {
954
+ const { worktrees } = makeTrackedMarkerProject();
955
+ for (const wt of worktrees) {
956
+ expect(readFileSync(join(wt, '.mx-coordination-team'), 'utf-8')).toBe('product\n');
957
+ expect(defaultTrackedCoordinationFiles(wt)).toEqual(['.mx-coordination-team']);
958
+ }
959
+ });
960
+ for (const index of [0, 1]) {
961
+ it(`worktree ${index + 1}: the token path requests nothing, caches nothing, and names the remedy`, async () => {
962
+ const { main, worktrees } = makeTrackedMarkerProject();
963
+ const wt = worktrees[index];
964
+ process.env.MX_PROJECT_ROOT = main;
965
+ plainShellAt(wt);
966
+ const fetchCredential = issued();
967
+ const res = await resolveCoordinationToken(plainShellTokenDeps(fetchCredential));
968
+ expect(res.status).toBe('misconfigured');
969
+ expect(res.token).toBeUndefined();
970
+ expect(res.slug).toBeUndefined();
971
+ // The reason, then the whole remedy, once.
972
+ expect(res.detail).toBe(`the .mx-coordination-team marker in ${wt} is tracked or staged in git on the branch that worktree has checked out, so it is not that worktree's own marker and was not used. ${TRACKED_REMEDY.join(' ')}`);
973
+ const refreshed = await refreshCoordinationToken('rejected-token-not-real', plainShellTokenDeps(fetchCredential));
974
+ expect(refreshed.status).toBe('misconfigured');
975
+ expect(fetchCredential).not.toHaveBeenCalled();
976
+ expect(cacheFilesIn(wt)).toEqual([]);
977
+ });
978
+ it(`worktree ${index + 1}: status prints no resolved team and no Ready`, async () => {
979
+ const { main, worktrees } = makeTrackedMarkerProject();
980
+ const wt = worktrees[index];
981
+ process.env.MX_PROJECT_ROOT = main;
982
+ plainShellAt(wt);
983
+ // The real token path, so nothing in this test hands status a credential.
984
+ await runStatus({ fetch: okFetch(), registration: { ...noOffline } });
985
+ const out = logs.join('\n');
986
+ expect(out).toContain('Team: not set');
987
+ expect(out).not.toMatch(/Team: +product/);
988
+ expect(out).not.toContain('✓ Ready');
989
+ expect(out).not.toContain('Token cached: yes');
990
+ expect(out).toContain('Registered: unverified (source: no roster consulted: no team was resolved)');
991
+ // The reason once, on the Status line. The remedy once, under it. Neither
992
+ // a second time through the token path.
993
+ expect(out.split('is tracked or staged in git on the branch that worktree has checked out')).toHaveLength(2);
994
+ for (const line of TRACKED_REMEDY)
995
+ expect(out.split(line)).toHaveLength(2);
996
+ expect(out).not.toContain('The live service gave no answer either');
997
+ expect(out).toContain('No team was looked up, because the marker in this worktree was not used.');
998
+ expect(out).not.toContain('No team marker was found');
999
+ expect(out).not.toContain('this directory names none');
1000
+ expect(cacheFilesIn(wt)).toEqual([]);
1001
+ });
1002
+ it(`worktree ${index + 1}: escalate exits 1 and sends nothing; memory mode does not use the marker`, async () => {
1003
+ const { main, worktrees } = makeTrackedMarkerProject();
1004
+ const wt = worktrees[index];
1005
+ process.env.MX_PROJECT_ROOT = main;
1006
+ plainShellAt(wt);
1007
+ const enqueue = vi.fn(async () => ({ messageId: 'never', duplicate: false }));
1008
+ await expect(runEscalate({ to: 'product', priority: 'p2', body: 'hello' }, { client: recordingClient(enqueue) }))
1009
+ .rejects.toThrow('process.exit(1)');
1010
+ expect(enqueue).not.toHaveBeenCalled();
1011
+ const out = errs.join('\n');
1012
+ expect(out.split('is tracked or staged in git on the branch that worktree has checked out')).toHaveLength(2);
1013
+ for (const line of TRACKED_REMEDY)
1014
+ expect(out.split(line)).toHaveLength(2);
1015
+ expect(out).not.toContain('No team marker was found');
1016
+ expect(resolveMemoryTeam()).not.toBe('product');
1017
+ });
1018
+ }
1019
+ it('the main-checkout listing shows neither worktree as (team product): both are under the not-usable list with the reason', () => {
1020
+ const { main, worktrees } = makeTrackedMarkerProject();
1021
+ const lines = markerNextStep({ ok: false, reason: 'main-checkout', top: main, detail: '' }, { projectRoot: () => main });
1022
+ const text = lines.join('\n');
1023
+ expect(text).not.toContain('(team product)');
1024
+ expect(listMarkedWorktrees(main)).toEqual([]);
1025
+ expect(text).toContain('These worktrees are not usable as they are:');
1026
+ // A short reason per worktree, and the remedy once under the list.
1027
+ for (const wt of worktrees) {
1028
+ expect(lines).toContain(` the .mx-coordination-team marker in ${wt} is tracked or staged in git on the branch that worktree has checked out, so it is not that worktree's own marker and was not used`);
1029
+ }
1030
+ for (const line of TRACKED_REMEDY)
1031
+ expect(text.split(line)).toHaveLength(2);
1032
+ expect(lines.slice(-TRACKED_REMEDY.length)).toEqual([...TRACKED_REMEDY]);
1033
+ });
1034
+ it('a tracked credential cache file refuses the worktree too, with no file name from disk next to a command', async () => {
1035
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
1036
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
1037
+ writeFileSync(join(worktree, '.mx-coordination-token--life-planner--alpha'), 'committed-token-not-real\n');
1038
+ git(worktree, 'add', '-f', '.mx-coordination-token--life-planner--alpha');
1039
+ git(worktree, 'commit', '-q', '-m', 'a cache file committed by mistake');
1040
+ const fetchCredential = issued();
1041
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate: { cwd: worktree, projectRoot: () => main } });
1042
+ expect(res.status).toBe('misconfigured');
1043
+ expect(res.token).toBeUndefined();
1044
+ expect(res.detail).toContain(`a credential cache file (.mx-coordination-token--*) in ${worktree} is tracked or staged in git on the branch that worktree has checked out, so the marker and the cache there were not used. ${TRACKED_REMEDY[0]}`);
1045
+ expect(res.detail).not.toContain('life-planner--alpha');
1046
+ expect(fetchCredential).not.toHaveBeenCalled();
1047
+ });
1048
+ it('when git cannot say whether the marker is tracked, the marker is refused (could not check is not checked)', async () => {
1049
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
1050
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
1051
+ const locate = { cwd: worktree, projectRoot: () => main, trackedFiles: () => undefined };
1052
+ const read = readTeamMarker({ root: worktree, source: 'git-toplevel' }, locate);
1053
+ expect(read).toMatchObject({ kind: 'refused', reason: 'tracked-unknown' });
1054
+ const fetchCredential = issued();
1055
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate });
1056
+ expect(res.status).toBe('misconfigured');
1057
+ expect(res.detail).toBe(`git could not say whether the .mx-coordination-team marker in ${worktree} is tracked or staged, so the marker was not used. Run \`git ls-files\` in that directory to see the error.`);
1058
+ expect(fetchCredential).not.toHaveBeenCalled();
1059
+ });
1060
+ it('the tracked question runs through the hardened git call: argv array, stripped environment, timeout; a failure is undefined', () => {
1061
+ process.env.MX_COORD_SERVICE_TOKEN = 'fake-service-token';
1062
+ process.env.MX_COORD_ADMIN_TOKEN = 'fake-admin-token';
1063
+ process.env.MX_API_KEY = 'fake-user-key';
1064
+ const calls = [];
1065
+ const exec = (file, args, options) => { calls.push({ file, args, options }); return '.mx-coordination-team\0.mx-coordination-token--p--t\0'; };
1066
+ expect(defaultTrackedCoordinationFiles('/p/.worktrees/a', exec)).toEqual(['.mx-coordination-team', '.mx-coordination-token--p--t']);
1067
+ expect(calls).toHaveLength(1);
1068
+ expect(calls[0].file).toBe('git');
1069
+ expect(calls[0].args).toEqual(['-c', 'core.fsmonitor=false', 'ls-files', '-z', '--', ':(icase).mx-coordination-team', ':(icase).mx-coordination-token--*']);
1070
+ expect(calls[0].options.cwd).toBe('/p/.worktrees/a');
1071
+ expect(calls[0].options.timeout).toBe(5_000);
1072
+ expect(calls[0].options).not.toHaveProperty('shell');
1073
+ for (const k of ['MX_COORD_SERVICE_TOKEN', 'MX_COORD_ADMIN_TOKEN', 'MX_API_KEY'])
1074
+ expect(calls[0].options.env).not.toHaveProperty(k);
1075
+ expect(defaultTrackedCoordinationFiles('/p', () => { throw new Error('timed out'); })).toBeUndefined();
1076
+ expect(defaultTrackedCoordinationFiles('/p', () => '')).toEqual([]);
1077
+ });
1078
+ it('CLAUDE_WORKTREE_PATH set: the tracked marker is used exactly as at 082c7d8 (this PR does not fix sessions, #527 does)', async () => {
1079
+ const { main, worktrees } = makeTrackedMarkerProject();
1080
+ const wt = worktrees[0];
1081
+ writeFileSync(join(wt, '.mx-code-context.json'), JSON.stringify({ team: 'personal-coach' }));
1082
+ process.env.MX_PROJECT_ROOT = main;
1083
+ process.env.CLAUDE_WORKTREE_PATH = wt;
1084
+ plainShellAt(wt);
1085
+ expect(readTeamMarker({ root: wt, source: 'CLAUDE_WORKTREE_PATH' })).toEqual({ kind: 'ok', line: 'product' });
1086
+ const fetchCredential = issued();
1087
+ const res = await resolveCoordinationToken({ ...plainShellTokenDeps(fetchCredential), writeCache: () => true });
1088
+ expect(res.status).toBe('resolved');
1089
+ expect(res.slug).toBe('product');
1090
+ expect(fetchCredential.mock.calls[0][0].team).toBe('product');
1091
+ expect(resolveMemoryTeam()).toBe('product');
1092
+ const enqueue = vi.fn(async () => ({ messageId: 'm1', duplicate: false }));
1093
+ await runEscalate({ to: 'engineering', priority: 'p2', body: 'hello' }, { client: recordingClient(enqueue) });
1094
+ expect(enqueue).toHaveBeenCalledWith(expect.objectContaining({ from: 'product' }));
1095
+ await runStatus({ fetch: okFetch(), registration: { client: recordingClient(enqueue), ...noOffline } });
1096
+ expect(logs.join('\n')).toMatch(/Team: {14}product\n/);
1097
+ });
1098
+ });
1099
+ describe('red-team finding 1: a cwd-located marker that disagrees with .mx-code-context.json names no team', () => {
1100
+ const okFetch = () => vi.fn(async (_url) => new Response('ok', { status: 200 }));
1101
+ /** An UNTRACKED marker `product` in a worktree whose code-context file says `personal-coach`. */
1102
+ function mismatch() {
1103
+ const { main, worktree } = makeProject('life-planner', 'life-planner', ['personal-coach-20260927']);
1104
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'product\n');
1105
+ writeFileSync(join(worktree, '.mx-code-context.json'), JSON.stringify({ product: 'life-planner', team: 'personal-coach' }));
1106
+ process.env.MX_PROJECT_ROOT = main;
1107
+ plainShellAt(worktree);
1108
+ return { main, worktree };
1109
+ }
1110
+ it('the token path requests nothing, caches nothing, and names both values and both files', async () => {
1111
+ const { worktree } = mismatch();
1112
+ const fetchCredential = issued();
1113
+ const res = await resolveCoordinationToken(plainShellTokenDeps(fetchCredential));
1114
+ expect(res.status).toBe('identity-mismatch');
1115
+ expect(res.token).toBeUndefined();
1116
+ expect(res.detail).toContain(`the .mx-coordination-team marker in ${worktree} names team "product" and .mx-code-context.json in the same worktree names team "personal-coach"`);
1117
+ const refreshed = await refreshCoordinationToken('rejected-token-not-real', plainShellTokenDeps(fetchCredential));
1118
+ expect(refreshed.status).toBe('identity-mismatch');
1119
+ expect(fetchCredential).not.toHaveBeenCalled();
1120
+ expect(cacheFilesIn(worktree)).toEqual([]);
1121
+ });
1122
+ it('status prints no resolved team and no Ready; escalate exits 1; memory mode and the listing do not use the marker', async () => {
1123
+ const { main, worktree } = mismatch();
1124
+ await runStatus({ fetch: okFetch(), registration: { ...noOffline } });
1125
+ const out = logs.join('\n');
1126
+ expect(out).toContain('Team: not set');
1127
+ expect(out).not.toMatch(/Team: +product/);
1128
+ expect(out).not.toContain('✓ Ready');
1129
+ expect(out).toContain('names team "product" and .mx-code-context.json in the same worktree names team "personal-coach"');
1130
+ expect(out).not.toContain('No team marker was found');
1131
+ const enqueue = vi.fn(async () => ({ messageId: 'never', duplicate: false }));
1132
+ await expect(runEscalate({ to: 'product', priority: 'p2', body: 'hello' }, { client: recordingClient(enqueue) }))
1133
+ .rejects.toThrow('process.exit(1)');
1134
+ expect(enqueue).not.toHaveBeenCalled();
1135
+ expect(errs.join('\n')).toContain('names team "product"');
1136
+ expect(resolveMemoryTeam()).not.toBe('product');
1137
+ const text = markerNextStep({ ok: false, reason: 'main-checkout', top: main, detail: '' }, { projectRoot: () => main }).join('\n');
1138
+ expect(text).not.toContain('(team product)');
1139
+ expect(text).toContain('These worktrees are not usable as they are:');
1140
+ expect(cacheFilesIn(worktree)).toEqual([]);
1141
+ });
1142
+ const controls = [
1143
+ ['no code-context file', undefined],
1144
+ ['a code-context file that agrees', (wt) => writeFileSync(join(wt, '.mx-code-context.json'), JSON.stringify({ team: 'alpha' }))],
1145
+ ['a code-context file that is not JSON', (wt) => writeFileSync(join(wt, '.mx-code-context.json'), '{ not json')],
1146
+ ['a code-context file with no team', (wt) => writeFileSync(join(wt, '.mx-code-context.json'), JSON.stringify({ product: 'life-planner' }))],
1147
+ ['a code-context file whose team is not a valid slug', (wt) => writeFileSync(join(wt, '.mx-code-context.json'), JSON.stringify({ team: 'Not A Slug\x1b[31m' }))],
1148
+ ['a code-context file that is a symbolic link (unreadable, so not evidence)', (wt) => {
1149
+ writeFileSync(join(base, 'elsewhere.json'), JSON.stringify({ team: 'beta' }));
1150
+ symlinkSync(join(base, 'elsewhere.json'), join(wt, '.mx-code-context.json'));
1151
+ }],
1152
+ ];
1153
+ for (const [label, setup] of controls) {
1154
+ it(`control: an untracked marker with ${label} resolves the marker's team`, async () => {
1155
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
1156
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
1157
+ setup?.(worktree);
1158
+ expect(readTeamMarker({ root: worktree, source: 'git-toplevel' })).toEqual({ kind: 'ok', line: 'alpha' });
1159
+ const fetchCredential = issued();
1160
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate: { cwd: worktree, projectRoot: () => main } });
1161
+ expect(res.status).toBe('resolved');
1162
+ expect(res.slug).toBe('alpha');
1163
+ expect(fetchCredential.mock.calls[0][0].team).toBe('alpha');
1164
+ });
1165
+ }
1166
+ });
1167
+ describe.skipIf(typeof process.getuid !== 'function')('round 4 small items', () => {
1168
+ it('N09: more than 20 refused worktrees print 20 and a count of the rest', () => {
1169
+ const { main } = makeProject('life-planner', 'life-planner', []);
1170
+ for (let i = 0; i < 25; i++)
1171
+ chmodSync(fakeWorktree(main, `gw${String(i).padStart(2, '0')}`, 'alpha\n'), 0o775);
1172
+ const lines = markerNextStep({ ok: false, reason: 'main-checkout', top: main, detail: '' }, { projectRoot: () => main, ...NOT_TRACKED });
1173
+ const at = lines.indexOf('These worktrees are not usable as they are:');
1174
+ expect(at).toBeGreaterThan(-1);
1175
+ const refused = lines.slice(at + 1);
1176
+ expect(refused.filter((l) => l.includes('is group- or world-writable (mode 775)'))).toHaveLength(20);
1177
+ expect(refused[refused.length - 1]).toBe(' and 5 more');
1178
+ expect(refused).toHaveLength(21);
1179
+ });
1180
+ it('a symbolic link under .worktrees/ is reported as a link, with no chmod advice and no team', () => {
1181
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
1182
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
1183
+ const link = join(main, '.worktrees', 'linked');
1184
+ symlinkSync(worktree, link);
1185
+ const lines = markerNextStep({ ok: false, reason: 'main-checkout', top: main, detail: '' }, { projectRoot: () => main });
1186
+ const about = lines.filter((l) => l.includes(link));
1187
+ expect(about).toEqual([` ${link} is a symbolic link, not a worktree directory, so it was not used; run the command from the directory it points to`]);
1188
+ expect(lines.join('\n')).not.toContain('mode 777');
1189
+ expect(lines.join('\n')).not.toContain('chmod');
1190
+ // The real directory is still listed, once, under its own path.
1191
+ expect(lines).toContain(` ${worktree} (team alpha)`);
1192
+ });
1193
+ });
1194
+ // ── Fix round 5: reviews at 2b8c8fd ─────────────────────────────────────
1195
+ /**
1196
+ * Run, in `dir`, every git command the remedy prints, exactly as printed,
1197
+ * through a shell. This is what an operator who follows the text does.
1198
+ */
1199
+ function runPrintedGitCommands(dir) {
1200
+ const commands = TRACKED_REMEDY.flatMap((line) => [...line.matchAll(/`(git [^`]+)`/g)].map((m) => m[1]));
1201
+ for (const command of commands) {
1202
+ const r = spawnSync('bash', ['-c', command], { cwd: dir, encoding: 'utf-8' });
1203
+ if (r.status !== 0)
1204
+ throw new Error(`${command}: ${r.stderr}`);
1205
+ }
1206
+ return commands;
1207
+ }
1208
+ /** Step 2 of the remedy: the two ignore lines it names, committed on the worktree's branch. */
1209
+ function addPrintedIgnoreRulesAndCommit(dir) {
1210
+ const rules = [...TRACKED_REMEDY[2].matchAll(/`([^`]+)`/g)].map((m) => m[1]);
1211
+ expect(rules).toEqual(['.mx-coordination-team', '.mx-coordination-token--*']);
1212
+ writeFileSync(join(dir, '.gitignore'), `${readFileSync(join(dir, '.gitignore'), 'utf-8')}${rules.join('\n')}\n`);
1213
+ git(dir, 'add', '.gitignore');
1214
+ git(dir, 'commit', '-q', '-m', 'stop tracking the coordination marker');
1215
+ }
1216
+ /** Steps 3 and 4: delete the leftover file, then what `mx-agent start <team>` does to the marker (start.ts step 5a). */
1217
+ function deleteLeftoverThenStartWritesMarker(dir, team) {
1218
+ rmSync(join(dir, '.mx-coordination-team'), { force: true });
1219
+ if (!existsSync(join(dir, '.mx-coordination-team')))
1220
+ writeFileSync(join(dir, '.mx-coordination-team'), team);
1221
+ }
1222
+ describe('QA M2, red-team A and C: the tracked-file remedy works when followed exactly', () => {
1223
+ const tokenIn = (main, wt, fetchCredential) => resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate: { cwd: wt, projectRoot: () => main } });
1224
+ it('the remedy names both files, both ignore rules, the per-branch scope, and what start does', () => {
1225
+ const text = TRACKED_REMEDY.join('\n');
1226
+ expect(text).toContain("`git rm --cached -f --ignore-unmatch -- .mx-coordination-team '.mx-coordination-token--*'`");
1227
+ expect(text).toContain('`.mx-coordination-team` and `.mx-coordination-token--*`');
1228
+ expect(text).toContain('Git tracks files per branch and every worktree has its own branch');
1229
+ expect(text).toContain('Every other worktree stays refused until its own branch stops tracking the files');
1230
+ expect(text).toContain('Delete the .mx-coordination-team file left in that worktree');
1231
+ expect(text).toContain('for a worktree directory named <team>-<date>, the part before the date');
1232
+ expect(text).toContain('then opens a session');
1233
+ // Constants only: nothing from disk can be inside a printed command.
1234
+ expect([...text.matchAll(/`([^`]+)`/g)].map((m) => m[1])).toEqual([
1235
+ "git rm --cached -f --ignore-unmatch -- .mx-coordination-team '.mx-coordination-token--*'",
1236
+ '.mx-coordination-team',
1237
+ '.mx-coordination-token--*',
1238
+ 'mx-agent start <team>',
1239
+ 'start',
1240
+ ]);
1241
+ });
1242
+ it('two existing worktrees on their own branches: the one where the steps are followed resolves, the other stays refused', async () => {
1243
+ const { main, worktrees } = makeTrackedMarkerProject();
1244
+ const [first, second] = worktrees;
1245
+ expect((await tokenIn(main, first, issued())).status).toBe('misconfigured');
1246
+ // Steps 1 to 4, in the first worktree, as printed.
1247
+ expect(runPrintedGitCommands(first)).toHaveLength(1);
1248
+ addPrintedIgnoreRulesAndCommit(first);
1249
+ deleteLeftoverThenStartWritesMarker(first, 'personal-coach');
1250
+ const fetchCredential = issued();
1251
+ const fixed = await tokenIn(main, first, fetchCredential);
1252
+ expect(fixed.status).toBe('resolved');
1253
+ expect(fixed.slug).toBe('personal-coach');
1254
+ expect(fetchCredential.mock.calls[0][0].team).toBe('personal-coach');
1255
+ // The second worktree is on its own branch. Nothing was done there.
1256
+ const untouched = issued();
1257
+ const still = await tokenIn(main, second, untouched);
1258
+ expect(still.status).toBe('misconfigured');
1259
+ expect(untouched).not.toHaveBeenCalled();
1260
+ const listing = markerNextStep({ ok: false, reason: 'main-checkout', top: main, detail: '' }, { projectRoot: () => main });
1261
+ expect(listing).toContain(` ${first} (team personal-coach)`);
1262
+ expect(listing.join('\n')).not.toContain(`${second} (team`);
1263
+ });
1264
+ it('the QA M2 path stays refused: the untrack commit on the base branch alone does not reach an existing worktree', async () => {
1265
+ const { main, worktrees } = makeTrackedMarkerProject();
1266
+ const [first] = worktrees;
1267
+ // What QA did at 2b8c8fd: steps 1 and 2 on the base branch, steps 3 and 4 in the worktree.
1268
+ runPrintedGitCommands(main);
1269
+ addPrintedIgnoreRulesAndCommit(main);
1270
+ deleteLeftoverThenStartWritesMarker(first, 'personal-coach');
1271
+ const fetchCredential = issued();
1272
+ const res = await tokenIn(main, first, fetchCredential);
1273
+ expect(res.status).toBe('misconfigured');
1274
+ expect(fetchCredential).not.toHaveBeenCalled();
1275
+ });
1276
+ it('the other route the remedy names: merging the branch that holds the commit, then steps 3 and 4', async () => {
1277
+ const { main, worktrees } = makeTrackedMarkerProject();
1278
+ const [first, second] = worktrees;
1279
+ runPrintedGitCommands(first);
1280
+ addPrintedIgnoreRulesAndCommit(first);
1281
+ git(second, 'merge', '-q', '--no-edit', 'worktree/personal-coach-20260927');
1282
+ expect(defaultTrackedCoordinationFiles(second)).toEqual([]);
1283
+ deleteLeftoverThenStartWritesMarker(second, 'engineering');
1284
+ const res = await tokenIn(main, second, issued());
1285
+ expect(res.status).toBe('resolved');
1286
+ expect(res.slug).toBe('engineering');
1287
+ });
1288
+ it('a credential cache file that is staged and not committed is refused as tracked or staged, and step 1 clears it', async () => {
1289
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
1290
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
1291
+ const cache = join(worktree, '.mx-coordination-token--life-planner--alpha');
1292
+ writeFileSync(cache, 'staged-token-not-real\n', { mode: 0o600 });
1293
+ // What `mx-agent start` does where no ignore rule covers the cache (start.ts, `git add -A`).
1294
+ git(worktree, 'add', '-A');
1295
+ // The file changes after it was staged, as a refreshed token would change it.
1296
+ writeFileSync(cache, 'rotated-token-not-real\n', { mode: 0o600 });
1297
+ const refusedFetch = issued();
1298
+ const refused = await tokenIn(main, worktree, refusedFetch);
1299
+ expect(refused.status).toBe('misconfigured');
1300
+ expect(refused.detail).toContain('is tracked or staged in git on the branch that worktree has checked out');
1301
+ expect(refused.detail).not.toContain('life-planner--alpha');
1302
+ expect(refusedFetch).not.toHaveBeenCalled();
1303
+ runPrintedGitCommands(worktree);
1304
+ expect(existsSync(cache)).toBe(true);
1305
+ const fetchCredential = issued();
1306
+ const res = await tokenIn(main, worktree, fetchCredential);
1307
+ expect(res.status).toBe('resolved');
1308
+ expect(res.source).toBe('cache');
1309
+ expect(fetchCredential).not.toHaveBeenCalled();
1310
+ });
1311
+ });
1312
+ describe('security review at 2b8c8fd: the git calls', () => {
1313
+ /** A script that leaves a sentinel file when git runs it. */
1314
+ function sentinelScript(name) {
1315
+ const sentinel = join(base, `${name}.ran`);
1316
+ const script = join(base, `${name}.sh`);
1317
+ writeFileSync(script, `#!/bin/sh\necho ran >> '${sentinel}'\n`, { mode: 0o755 });
1318
+ return { script, sentinel };
1319
+ }
1320
+ it('Should Fix 1: a repository whose config sets core.fsmonitor to a program does not get it run', () => {
1321
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
1322
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
1323
+ const { script, sentinel } = sentinelScript('fsmonitor');
1324
+ git(main, 'config', 'core.fsmonitor', script);
1325
+ // The fixture is real: plain git runs the program when it reads the index.
1326
+ spawnSync('git', ['ls-files'], { cwd: worktree, encoding: 'utf-8' });
1327
+ expect(existsSync(sentinel)).toBe(true);
1328
+ rmSync(sentinel);
1329
+ expect(locateCoordinationWorktree({}, { cwd: worktree, projectRoot: () => main }).ok).toBe(true);
1330
+ expect(readTeamMarker({ root: worktree, source: 'git-toplevel' })).toEqual({ kind: 'ok', line: 'alpha' });
1331
+ expect(defaultTrackedCoordinationFiles(worktree)).toEqual([]);
1332
+ expect(listMarkedWorktrees(main)).toEqual([{ path: worktree, team: 'alpha' }]);
1333
+ expect(existsSync(sentinel)).toBe(false);
1334
+ });
1335
+ it('no other program-valued config key runs a program through the two git commands this module uses', () => {
1336
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
1337
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
1338
+ writeFileSync(join(worktree, '.gitattributes'), '* filter=probe diff=probe\n');
1339
+ const { script, sentinel } = sentinelScript('config');
1340
+ const hooks = join(base, 'hooks');
1341
+ mkdirSync(hooks);
1342
+ for (const hook of ['post-index-change', 'reference-transaction', 'post-checkout', 'pre-auto-gc']) {
1343
+ writeFileSync(join(hooks, hook), `#!/bin/sh\necho ran >> '${sentinel}'\n`, { mode: 0o755 });
1344
+ }
1345
+ for (const [key, value] of [
1346
+ ['core.pager', script], ['pager.ls-files', script], ['pager.rev-parse', script],
1347
+ ['core.editor', script], ['core.sshCommand', script], ['core.askPass', script],
1348
+ ['credential.helper', `!${script}`], ['core.hooksPath', hooks],
1349
+ ['filter.probe.clean', script], ['filter.probe.smudge', script], ['filter.probe.process', script],
1350
+ ['diff.probe.textconv', script], ['diff.external', script], ['core.alternateRefsCommand', script],
1351
+ ['alias.ls-files', `!${script}`], ['alias.rev-parse', `!${script}`],
1352
+ ])
1353
+ git(main, 'config', key, value);
1354
+ expect(locateCoordinationWorktree({}, { cwd: worktree, projectRoot: () => main }))
1355
+ .toEqual({ ok: true, root: worktree, source: 'git-toplevel' });
1356
+ expect(readTeamMarker({ root: worktree, source: 'git-toplevel' })).toEqual({ kind: 'ok', line: 'alpha' });
1357
+ expect(existsSync(sentinel)).toBe(false);
1358
+ });
1359
+ it('Should Fix 2: a marker tracked under another letter case is refused', () => {
1360
+ const { worktree } = makeProject('life-planner', 'life-planner');
1361
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
1362
+ writeFileSync(join(worktree, '.MX-Coordination-Team'), 'product\n');
1363
+ git(worktree, 'add', '-f', '.MX-Coordination-Team');
1364
+ expect(defaultTrackedCoordinationFiles(worktree)).toEqual(['.MX-Coordination-Team']);
1365
+ expect(readTeamMarker({ root: worktree, source: 'git-toplevel' })).toMatchObject({ kind: 'refused', reason: 'tracked' });
1366
+ });
1367
+ it('Should Fix 2: a cache file tracked under another letter case is refused', () => {
1368
+ const { worktree } = makeProject('life-planner', 'life-planner');
1369
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
1370
+ writeFileSync(join(worktree, '.MX-COORDINATION-TOKEN--life-planner--alpha'), 'committed-token-not-real\n');
1371
+ git(worktree, 'add', '-f', '.MX-COORDINATION-TOKEN--life-planner--alpha');
1372
+ expect(readTeamMarker({ root: worktree, source: 'git-toplevel' })).toMatchObject({ kind: 'refused', reason: 'tracked' });
1373
+ });
1374
+ it('Informational 1: GIT_LITERAL_PATHSPECS in the operator environment does not hide a tracked cache file', async () => {
1375
+ const { main, worktree } = makeProject('life-planner', 'life-planner');
1376
+ writeFileSync(join(worktree, '.mx-coordination-team'), 'alpha\n');
1377
+ writeFileSync(join(worktree, '.mx-coordination-token--life-planner--alpha'), 'committed-token-not-real\n');
1378
+ git(worktree, 'add', '-f', '.mx-coordination-token--life-planner--alpha');
1379
+ process.env.GIT_LITERAL_PATHSPECS = '1';
1380
+ process.env.GIT_NOGLOB_PATHSPECS = '1';
1381
+ expect(defaultTrackedCoordinationFiles(worktree)).toEqual(['.mx-coordination-token--life-planner--alpha']);
1382
+ const fetchCredential = issued();
1383
+ const res = await resolveCoordinationToken({ env: {}, ...credentialDeps(fetchCredential), locate: { cwd: worktree, projectRoot: () => main } });
1384
+ expect(res.status).toBe('misconfigured');
1385
+ expect(res.token).toBeUndefined();
1386
+ expect(fetchCredential).not.toHaveBeenCalled();
1387
+ });
1388
+ it('Informational 1: the four pathspec variables are removed from every git child environment', () => {
1389
+ expect([...GIT_PATHSPEC_ENV].sort()).toEqual(['GIT_GLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS', 'GIT_LITERAL_PATHSPECS', 'GIT_NOGLOB_PATHSPECS']);
1390
+ for (const k of GIT_PATHSPEC_ENV)
1391
+ process.env[k] = '1';
1392
+ const envs = [];
1393
+ const exec = (_file, args, options) => {
1394
+ envs.push(options.env);
1395
+ if (args.includes('ls-files'))
1396
+ return '';
1397
+ return '/p/.worktrees/a\n/p/.git/worktrees/a\n/p/.git\n';
1398
+ };
1399
+ defaultTrackedCoordinationFiles('/p/.worktrees/a', exec);
1400
+ defaultGitTopology('/p/.worktrees/a', exec);
1401
+ expect(envs).toHaveLength(2);
1402
+ for (const env of envs)
1403
+ for (const k of GIT_PATHSPEC_ENV)
1404
+ expect(env).not.toHaveProperty(k);
1405
+ });
1406
+ });
1407
+ //# sourceMappingURL=coordination-plain-shell-commands.test.js.map