@memnexus-ai/mx-agent-cli 0.1.231 → 0.1.233
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__tests__/behavioral-extraction.test.js +93 -0
- package/dist/__tests__/behavioral-extraction.test.js.map +1 -1
- package/dist/__tests__/behavioral-injection.test.d.ts +13 -0
- package/dist/__tests__/behavioral-injection.test.d.ts.map +1 -0
- package/dist/__tests__/behavioral-injection.test.js +384 -0
- package/dist/__tests__/behavioral-injection.test.js.map +1 -0
- package/dist/__tests__/bootstrap-behavioral-contract.test.d.ts +18 -0
- package/dist/__tests__/bootstrap-behavioral-contract.test.d.ts.map +1 -0
- package/dist/__tests__/bootstrap-behavioral-contract.test.js +101 -0
- package/dist/__tests__/bootstrap-behavioral-contract.test.js.map +1 -0
- package/dist/__tests__/provision-behavioral-contract.test.d.ts +13 -0
- package/dist/__tests__/provision-behavioral-contract.test.d.ts.map +1 -0
- package/dist/__tests__/provision-behavioral-contract.test.js +454 -0
- package/dist/__tests__/provision-behavioral-contract.test.js.map +1 -0
- package/dist/__tests__/provision-copy-containment.test.d.ts +19 -0
- package/dist/__tests__/provision-copy-containment.test.d.ts.map +1 -0
- package/dist/__tests__/provision-copy-containment.test.js +187 -0
- package/dist/__tests__/provision-copy-containment.test.js.map +1 -0
- package/dist/__tests__/provision-teambuilder-flow.test.d.ts +22 -0
- package/dist/__tests__/provision-teambuilder-flow.test.d.ts.map +1 -0
- package/dist/__tests__/provision-teambuilder-flow.test.js +165 -0
- package/dist/__tests__/provision-teambuilder-flow.test.js.map +1 -0
- package/dist/__tests__/provision-write-integrity.test.d.ts +18 -0
- package/dist/__tests__/provision-write-integrity.test.d.ts.map +1 -0
- package/dist/__tests__/provision-write-integrity.test.js +141 -0
- package/dist/__tests__/provision-write-integrity.test.js.map +1 -0
- package/dist/__tests__/startup-report.test.js +3 -3
- package/dist/__tests__/startup-report.test.js.map +1 -1
- package/dist/agent-config/shared/eval-tiered-rigor.md +4 -2
- package/dist/commands/bootstrap.d.ts +2 -0
- package/dist/commands/bootstrap.d.ts.map +1 -1
- package/dist/commands/bootstrap.js +15 -1
- package/dist/commands/bootstrap.js.map +1 -1
- package/dist/commands/create.d.ts +188 -0
- package/dist/commands/create.d.ts.map +1 -1
- package/dist/commands/create.js +606 -23
- package/dist/commands/create.js.map +1 -1
- package/dist/commands/new.d.ts +2 -0
- package/dist/commands/new.d.ts.map +1 -1
- package/dist/commands/new.js +6 -1
- package/dist/commands/new.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -2
- package/dist/index.js.map +1 -1
- package/dist/lib/behavioral-injection.d.ts +144 -0
- package/dist/lib/behavioral-injection.d.ts.map +1 -0
- package/dist/lib/behavioral-injection.js +438 -0
- package/dist/lib/behavioral-injection.js.map +1 -0
- package/dist/lib/claude.d.ts +49 -7
- package/dist/lib/claude.d.ts.map +1 -1
- package/dist/lib/claude.js +62 -82
- package/dist/lib/claude.js.map +1 -1
- package/dist/lib/templates.d.ts +1 -1
- package/dist/lib/templates.d.ts.map +1 -1
- package/dist/lib/templates.js +2 -0
- package/dist/lib/templates.js.map +1 -1
- package/package.json +1 -1
package/dist/commands/create.js
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
* Creates a new agent team worktree, initialises team memories, and
|
|
5
5
|
* creates a catalog entry.
|
|
6
6
|
*/
|
|
7
|
-
import { existsSync, mkdirSync,
|
|
8
|
-
import { join, basename, dirname } from 'path';
|
|
7
|
+
import { closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, realpathSync, writeSync, } from 'fs';
|
|
8
|
+
import { join, basename, dirname, relative, isAbsolute, sep } from 'path';
|
|
9
9
|
import chalk from 'chalk';
|
|
10
10
|
import { findProjectRoot, assignSlot, getCurrentBranch, fetchOrigin, createGitWorktree, addToGitSafeDirectory, createHuskySymlink, generateBranchName, generateWorktreeDirName, } from '../lib/worktree.js';
|
|
11
11
|
import { syncClaudeConfig, deployClaudeMd, writeClaudeLocal, logSuccess, logWarning, logDim } from '../lib/claude.js';
|
|
@@ -13,6 +13,7 @@ import { writeTeamCatalog, slugToDisplayName } from '../lib/catalog.js';
|
|
|
13
13
|
import { isMxAvailable, bootstrapTeamMemories, logMemoryResult, teamMemorySpecs, logManualMemoryCommands } from '../lib/memory.js';
|
|
14
14
|
import { loadProjectConfig, resolveProjectConfig } from '../lib/project-config.js';
|
|
15
15
|
import { checkConfigGeneration } from '../lib/config-generation.js';
|
|
16
|
+
import { checkRoleguideMarkers, describeBehavioralProblem, BEHAVIORAL_START_MARKER, BEHAVIORAL_END_MARKER, } from '../lib/behavioral-injection.js';
|
|
16
17
|
/**
|
|
17
18
|
* Infer a team slug from a roleguide filename.
|
|
18
19
|
* e.g. "retrieval-leader.md" → "retrieval"
|
|
@@ -24,6 +25,508 @@ function inferSlugFromRoleguide(roleguide) {
|
|
|
24
25
|
// Strip common suffixes
|
|
25
26
|
return filename.replace(/-leader$/, '').replace(/-roleguide$/, '');
|
|
26
27
|
}
|
|
28
|
+
/**
|
|
29
|
+
* Re-anchor a validated source path under a destination root, and refuse if the
|
|
30
|
+
* result escapes it.
|
|
31
|
+
*
|
|
32
|
+
* MUST FIX, #4541 security review round 4 (pre-existing defect, tracked as #4571).
|
|
33
|
+
* The step-6b copy derived its destination from the RAW OPERATOR STRING:
|
|
34
|
+
*
|
|
35
|
+
* const dest = join(worktreePath, roleguide); // roleguide is user input
|
|
36
|
+
*
|
|
37
|
+
* `join` normalises `..` rather than rejecting it, so
|
|
38
|
+
* `--roleguide ../victim-team/.git/hooks/pre-commit` writes OUTSIDE the new
|
|
39
|
+
* worktree and into another team's worktree — violating the standing rule that no
|
|
40
|
+
* team touches another team's worktree, and, because `copyFileSync` preserved
|
|
41
|
+
* source mode, landing as an EXECUTABLE git hook that runs on the victim's next
|
|
42
|
+
* commit. Source containment does not help: a team-builder plants the payload in
|
|
43
|
+
* its own tree, which is a legitimately allowed root.
|
|
44
|
+
*
|
|
45
|
+
* The destination is therefore never built from operator input. It is built from
|
|
46
|
+
* the source path's position RELATIVE TO THE ROOT IT WAS VALIDATED UNDER, and the
|
|
47
|
+
* re-anchored result is verified to stay inside the realpath'd destination root.
|
|
48
|
+
*/
|
|
49
|
+
function reanchorContained(srcRoot, srcAbsPath, destRoot) {
|
|
50
|
+
let realSrcRoot;
|
|
51
|
+
let realDestRoot;
|
|
52
|
+
try {
|
|
53
|
+
realSrcRoot = realpathSync(srcRoot);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return { ok: false, detail: `source root ${srcRoot} does not resolve` };
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
realDestRoot = realpathSync(destRoot);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return { ok: false, detail: `destination root ${destRoot} does not resolve` };
|
|
63
|
+
}
|
|
64
|
+
const rel = relative(realSrcRoot, srcAbsPath);
|
|
65
|
+
if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
|
|
66
|
+
return {
|
|
67
|
+
ok: false,
|
|
68
|
+
detail: `${srcAbsPath} is not inside its validated root ${realSrcRoot} ` +
|
|
69
|
+
`(relative path resolved to "${rel}")`,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const dest = join(realDestRoot, rel);
|
|
73
|
+
if (!pathIsInside(dest, realDestRoot) || dest === realDestRoot) {
|
|
74
|
+
return { ok: false, detail: `destination ${dest} escapes ${realDestRoot}` };
|
|
75
|
+
}
|
|
76
|
+
return { ok: true, dest, rel };
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Create the parent directory of `dest`, confirm it still resolves inside
|
|
80
|
+
* `realDestRoot`, then create `dest` EXCLUSIVELY and write `bytes` to it as a
|
|
81
|
+
* non-executable regular file.
|
|
82
|
+
*
|
|
83
|
+
* THREE separate protections, each closing a case the others do not:
|
|
84
|
+
*
|
|
85
|
+
* 1. POST-MKDIR RE-VERIFICATION — `mkdirSync` follows a symlinked component
|
|
86
|
+
* happily, so containment is re-checked against the physical parent that
|
|
87
|
+
* actually exists before anything is written.
|
|
88
|
+
*
|
|
89
|
+
* 2. O_EXCL | O_NOFOLLOW ON THE FINAL COMPONENT (#4541 review round 5, MUST FIX).
|
|
90
|
+
* The previous `writeFileSync(finalDest, ...)` opened with `O_CREAT` and
|
|
91
|
+
* neither flag, so a symlink AT THE FINAL COMPONENT was followed. Both
|
|
92
|
+
* `pathIsInside` checks pass in that case — the lexical path is inside the
|
|
93
|
+
* root, only the resolution escapes — and the file lands wherever the link
|
|
94
|
+
* points. `O_NOFOLLOW` makes the kernel refuse (ELOOP) instead; `O_EXCL`
|
|
95
|
+
* makes creation atomic, so the check and the create are one syscall and a
|
|
96
|
+
* link planted after an earlier check cannot be raced into.
|
|
97
|
+
*
|
|
98
|
+
* The `existsSync` skip guards at the call sites are NOT this control and
|
|
99
|
+
* never were: `existsSync` FOLLOWS the link, so a DANGLING symlink returns
|
|
100
|
+
* false and execution proceeds straight to the write. `EEXIST` from this
|
|
101
|
+
* open is the control.
|
|
102
|
+
*
|
|
103
|
+
* Reachability is concrete, not theoretical: the destination worktree is
|
|
104
|
+
* created at step 4 and written at step 6b, with `fetchOrigin` and
|
|
105
|
+
* `syncClaudeConfig` — two network round-trips — in between; both the
|
|
106
|
+
* worktree path and the relative destination are deterministic; and
|
|
107
|
+
* `.worktrees/` is writable by every agent in the fleet. Note that the usual
|
|
108
|
+
* "an attacker who can write here could edit the file anyway" argument does
|
|
109
|
+
* NOT apply: the attacker writes into the brand-new, unowned destination
|
|
110
|
+
* worktree and uses it to escape to a THIRD location, which implies nothing
|
|
111
|
+
* about rights over the victim.
|
|
112
|
+
*
|
|
113
|
+
* 3. MODE FIXED AT 0644, never inherited. `copyFileSync` propagates the source
|
|
114
|
+
* file's mode, so a 0755 source — trivial for an attacker who controls a file
|
|
115
|
+
* in their own worktree — turns any path defect into code execution. A
|
|
116
|
+
* roleguide and a catalog entry are documentation; neither is executable.
|
|
117
|
+
*
|
|
118
|
+
* RESIDUAL — this list is not complete protection, and saying so is the point.
|
|
119
|
+
* `O_NOFOLLOW` guards the FINAL COMPONENT ONLY. Intermediate components of
|
|
120
|
+
* `realParent` that are swapped between the `realpathSync` above and the `openSync`
|
|
121
|
+
* below are still followed: the resolution and the open are separate syscalls on a
|
|
122
|
+
* path, and Node has no `openat`, so the window is not closable in pure Node. The
|
|
123
|
+
* same residual is stated for the READ path in behavioral-injection.ts, and the
|
|
124
|
+
* same conditional argument applies — winning the race needs write access to a
|
|
125
|
+
* directory inside the destination root, which for a freshly created worktree
|
|
126
|
+
* means an agent that can already write there. Ancestor containment is verified
|
|
127
|
+
* before `mkdirSync` and again after it, which narrows but does not remove it.
|
|
128
|
+
*
|
|
129
|
+
* Do not re-describe these as complete. A comment that lists protections while
|
|
130
|
+
* omitting a known residual is how the next refactor loses it.
|
|
131
|
+
*/
|
|
132
|
+
function writeContained(dest, realDestRoot, bytes) {
|
|
133
|
+
const parent = dirname(dest);
|
|
134
|
+
// PRE-MKDIR ancestor containment. `mkdirSync(..., { recursive: true })` follows
|
|
135
|
+
// symlinked components, so a symlinked ancestor made it CREATE DIRECTORIES
|
|
136
|
+
// outside the destination root even though the subsequent write was correctly
|
|
137
|
+
// refused: the write was contained, the directory creation was not. No content
|
|
138
|
+
// and no mode is involved, but a directory planted where another team's process
|
|
139
|
+
// expects a file — `<victim>/CLAUDE.local.md/` — is an EISDIR denial of service
|
|
140
|
+
// on that team's session start.
|
|
141
|
+
//
|
|
142
|
+
// Walk up to the deepest ancestor that already EXISTS and verify IT resolves
|
|
143
|
+
// inside the root. `existsSync` follows links, so a symlinked ancestor stops the
|
|
144
|
+
// walk at itself and its realpath is what gets checked.
|
|
145
|
+
let probe = parent;
|
|
146
|
+
while (!existsSync(probe)) {
|
|
147
|
+
const up = dirname(probe);
|
|
148
|
+
if (up === probe)
|
|
149
|
+
break;
|
|
150
|
+
probe = up;
|
|
151
|
+
}
|
|
152
|
+
let realProbe;
|
|
153
|
+
try {
|
|
154
|
+
realProbe = realpathSync(probe);
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return { ok: false, detail: `${probe} does not resolve — refusing to create directories` };
|
|
158
|
+
}
|
|
159
|
+
if (!pathIsInside(realProbe, realDestRoot)) {
|
|
160
|
+
return {
|
|
161
|
+
ok: false,
|
|
162
|
+
detail: `${probe} resolves to ${realProbe}, outside ${realDestRoot} — ` +
|
|
163
|
+
`refusing to create any directory`,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
mkdirSync(parent, { recursive: true });
|
|
168
|
+
}
|
|
169
|
+
catch (err) {
|
|
170
|
+
return { ok: false, detail: `could not create ${parent}: ${err instanceof Error ? err.message : String(err)}` };
|
|
171
|
+
}
|
|
172
|
+
let realParent;
|
|
173
|
+
try {
|
|
174
|
+
realParent = realpathSync(parent);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return { ok: false, detail: `${parent} does not resolve after creation` };
|
|
178
|
+
}
|
|
179
|
+
if (!pathIsInside(realParent, realDestRoot)) {
|
|
180
|
+
return {
|
|
181
|
+
ok: false,
|
|
182
|
+
detail: `${parent} resolves to ${realParent}, outside ${realDestRoot} — refusing to write`,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const finalDest = join(realParent, basename(dest));
|
|
186
|
+
if (!pathIsInside(finalDest, realDestRoot)) {
|
|
187
|
+
return { ok: false, detail: `${finalDest} escapes ${realDestRoot}` };
|
|
188
|
+
}
|
|
189
|
+
// Exclusive, no-follow create. Never `writeFileSync` by path here.
|
|
190
|
+
let fd;
|
|
191
|
+
try {
|
|
192
|
+
fd = openSync(finalDest, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o644);
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
const code = err?.code;
|
|
196
|
+
if (code === 'ELOOP') {
|
|
197
|
+
return {
|
|
198
|
+
ok: false,
|
|
199
|
+
detail: `${finalDest} is a symbolic link (ELOOP) — refusing to write through it`,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
if (code === 'EEXIST') {
|
|
203
|
+
return {
|
|
204
|
+
ok: false,
|
|
205
|
+
detail: `${finalDest} already exists (EEXIST) — refusing to overwrite. ` +
|
|
206
|
+
`A dangling symlink reports as absent to existsSync, so this refusal is ` +
|
|
207
|
+
`the control, not the caller's existence check.`,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
return {
|
|
211
|
+
ok: false,
|
|
212
|
+
detail: `could not create ${finalDest} (${code ?? 'unknown error'}): ` +
|
|
213
|
+
`${err instanceof Error ? err.message : String(err)}`,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
// SHORT WRITES. `write(2)` may return having written FEWER bytes than requested
|
|
217
|
+
// without throwing — ENOSPC being the realistic trigger. Discarding the return
|
|
218
|
+
// value reports a successful copy for a TRUNCATED file, and a roleguide truncated
|
|
219
|
+
// past its end marker is precisely the copy/injection divergence the single-read
|
|
220
|
+
// `raw` threading exists to prevent, reintroduced at the write side. Loop until
|
|
221
|
+
// every byte is on disk. Byte offsets, not character offsets — hence the Buffer.
|
|
222
|
+
const buf = Buffer.from(bytes, 'utf-8');
|
|
223
|
+
let writeFailure = null;
|
|
224
|
+
try {
|
|
225
|
+
let off = 0;
|
|
226
|
+
while (off < buf.length) {
|
|
227
|
+
const n = writeSync(fd, buf, off, buf.length - off);
|
|
228
|
+
if (n <= 0) {
|
|
229
|
+
writeFailure =
|
|
230
|
+
`short write to ${finalDest}: wrote ${off} of ${buf.length} bytes ` +
|
|
231
|
+
`(write returned ${n}) — file may be truncated`;
|
|
232
|
+
break;
|
|
233
|
+
}
|
|
234
|
+
off += n;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
writeFailure = `could not write ${finalDest}: ${err instanceof Error ? err.message : String(err)}`;
|
|
239
|
+
}
|
|
240
|
+
// CLOSE ERRORS. On filesystems that defer flushing, the write error surfaces at
|
|
241
|
+
// close; swallowing it reports a failed write as a successful copy.
|
|
242
|
+
let closeFailure = null;
|
|
243
|
+
try {
|
|
244
|
+
closeSync(fd);
|
|
245
|
+
}
|
|
246
|
+
catch (err) {
|
|
247
|
+
closeFailure = `could not close ${finalDest}: ${err instanceof Error ? err.message : String(err)}`;
|
|
248
|
+
}
|
|
249
|
+
if (writeFailure)
|
|
250
|
+
return { ok: false, detail: writeFailure };
|
|
251
|
+
if (closeFailure)
|
|
252
|
+
return { ok: false, detail: closeFailure };
|
|
253
|
+
return { ok: true };
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Refusal from the provisioning behavioral-block contract.
|
|
257
|
+
*
|
|
258
|
+
* A THROW, not a `process.exit` (#4541 security review, MUST FIX 3c).
|
|
259
|
+
* `mx-agent new project` wraps its `runCreate` call in a try/catch precisely so a
|
|
260
|
+
* provisioning failure degrades gracefully — it prints the manual re-run command
|
|
261
|
+
* and leaves the operator with a usable project. `process.exit` walks straight
|
|
262
|
+
* past that handler, and by the time provisioning runs the project directory, git
|
|
263
|
+
* repo, initial commit and possibly a `gh repo create` already exist, so an exit
|
|
264
|
+
* abandons a half-built project with no recovery path printed. The top-level
|
|
265
|
+
* `provision`/`create` actions already catch, print `err.message`, and exit 1 —
|
|
266
|
+
* so the operator-facing behaviour of a direct invocation is unchanged.
|
|
267
|
+
*/
|
|
268
|
+
export class BehavioralContractError extends Error {
|
|
269
|
+
code = 'behavioral-contract-refused';
|
|
270
|
+
constructor(message) {
|
|
271
|
+
super(message);
|
|
272
|
+
this.name = 'BehavioralContractError';
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
/** True when `candidate` is `root` or lies beneath it. Root is separator-normalised. */
|
|
276
|
+
function pathIsInside(candidate, root) {
|
|
277
|
+
if (candidate === root)
|
|
278
|
+
return true;
|
|
279
|
+
const prefix = root.endsWith(sep) ? root : root + sep;
|
|
280
|
+
return candidate.startsWith(prefix);
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Walk up from `dir` looking for the git worktree that encloses it (a directory
|
|
284
|
+
* containing `.git`, which is a FILE in a linked worktree and a directory in the
|
|
285
|
+
* main checkout). Returns the physical path, or null.
|
|
286
|
+
*/
|
|
287
|
+
function enclosingGitWorktree(dir) {
|
|
288
|
+
let cur;
|
|
289
|
+
try {
|
|
290
|
+
cur = realpathSync(dir);
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
for (let i = 0; i < 40; i++) {
|
|
296
|
+
if (existsSync(join(cur, '.git')))
|
|
297
|
+
return cur;
|
|
298
|
+
const parent = dirname(cur);
|
|
299
|
+
if (parent === cur)
|
|
300
|
+
return null;
|
|
301
|
+
cur = parent;
|
|
302
|
+
}
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* The directories a `--roleguide` argument may resolve inside.
|
|
307
|
+
*
|
|
308
|
+
* EXPLICIT, not implicit, and NOT caller-chosen (#4541 security review rounds 3
|
|
309
|
+
* and 4). Two roots, both anchored to project configuration:
|
|
310
|
+
*
|
|
311
|
+
* 1. The PROJECT ROOT — where a committed roleguide lives.
|
|
312
|
+
* 2. The git worktree ENCLOSING the caller's cwd, and only when that worktree
|
|
313
|
+
* sits inside the project's own worktree directory. This is the documented
|
|
314
|
+
* team-builder Step 6a flow (`team-builder.md:371`): the builder drafts a
|
|
315
|
+
* roleguide in its own worktree and provisions from there, before the file
|
|
316
|
+
* reaches the base branch. That flow needs exactly ONE extra root — the
|
|
317
|
+
* team-builder's worktree — not any directory on the filesystem.
|
|
318
|
+
*
|
|
319
|
+
* A previous revision used `process.cwd()` itself as root 2 and its comment
|
|
320
|
+
* claimed a path outside both roots "is REFUSED rather than read". That claim was
|
|
321
|
+
* FALSE, and demonstrably so: `cd /tmp/evil && mx-agent provision --roleguide
|
|
322
|
+
* /tmp/evil/rg.md` satisfied containment because the caller chose the directory
|
|
323
|
+
* that authorised it. A root the attacker selects is not a boundary. Anchoring to
|
|
324
|
+
* the project's worktree directory makes the set of acceptable roots a property of
|
|
325
|
+
* the project, not of the invocation.
|
|
326
|
+
*
|
|
327
|
+
* FAILS CLOSED: when cwd is not inside a git worktree under `<projectRoot>/<worktreeDir>`,
|
|
328
|
+
* the project root is the only root, and a relative `--roleguide` simply resolves
|
|
329
|
+
* there instead.
|
|
330
|
+
*/
|
|
331
|
+
function allowedRoleguideRoots(projectRoot, worktreeDir) {
|
|
332
|
+
const roots = [];
|
|
333
|
+
try {
|
|
334
|
+
roots.push(realpathSync(projectRoot));
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
roots.push(projectRoot);
|
|
338
|
+
}
|
|
339
|
+
let worktreesBase = null;
|
|
340
|
+
try {
|
|
341
|
+
worktreesBase = realpathSync(join(projectRoot, worktreeDir));
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
worktreesBase = null;
|
|
345
|
+
}
|
|
346
|
+
if (worktreesBase) {
|
|
347
|
+
const cwdWorktree = enclosingGitWorktree(process.cwd());
|
|
348
|
+
// Must be UNDER the worktrees directory, not the directory itself.
|
|
349
|
+
if (cwdWorktree && cwdWorktree !== worktreesBase && pathIsInside(cwdWorktree, worktreesBase)) {
|
|
350
|
+
if (!roots.includes(cwdWorktree))
|
|
351
|
+
roots.push(cwdWorktree);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
// MOST SPECIFIC FIRST. The roots NEST: `.worktrees/` lives inside the project
|
|
355
|
+
// root, so a roleguide in the team-builder's worktree is inside BOTH. Callers
|
|
356
|
+
// pick the first matching root, so an unsorted list makes the project root win
|
|
357
|
+
// every time and `relative()` then yields
|
|
358
|
+
// `.worktrees/builder-wt/mx-agent-system/roleguides/x.md` — a path that is
|
|
359
|
+
// contained but wrong, and which the roleguides-prefix check correctly refuses.
|
|
360
|
+
// The net effect was that the documented team-builder Step 6a flow
|
|
361
|
+
// (`team-builder.md:371`) shipped a new team with NO roleguide.
|
|
362
|
+
//
|
|
363
|
+
// Sorting by descending length makes the deepest containing root win, which is
|
|
364
|
+
// the only sensible reading of "the root this file belongs to". It also
|
|
365
|
+
// restores the documented resolution precedence for a RELATIVE --roleguide
|
|
366
|
+
// (the caller's own worktree before the project root), since resolveRoleguidePath
|
|
367
|
+
// walks this same list.
|
|
368
|
+
roots.sort((a, b) => b.length - a.length);
|
|
369
|
+
return roots;
|
|
370
|
+
}
|
|
371
|
+
function resolveRoleguidePath(roleguide, projectRoot, roots) {
|
|
372
|
+
const candidates = roleguide.startsWith('/')
|
|
373
|
+
? [roleguide]
|
|
374
|
+
: [
|
|
375
|
+
// Relative paths are tried against each ALLOWED ROOT, in the same order
|
|
376
|
+
// the roots are declared (project root first, then the team-builder's own
|
|
377
|
+
// worktree if it qualifies). Previously this tried `process.cwd()`
|
|
378
|
+
// directly, which is not one of the roots.
|
|
379
|
+
...roots.map((r) => join(r, roleguide)),
|
|
380
|
+
join(projectRoot, roleguide),
|
|
381
|
+
];
|
|
382
|
+
for (const c of candidates) {
|
|
383
|
+
if (!existsSync(c))
|
|
384
|
+
continue;
|
|
385
|
+
try {
|
|
386
|
+
// Resolve the PARENT only, then re-append the basename.
|
|
387
|
+
//
|
|
388
|
+
// Deliberately NOT `realpathSync(c)`. Realpath'ing the whole path collapses
|
|
389
|
+
// a symlinked FINAL component too, which silently follows the link here and
|
|
390
|
+
// hands checkRoleguideMarkers a path whose link-ness has already been
|
|
391
|
+
// erased — defeating its O_NOFOLLOW rejection entirely. Resolving only the
|
|
392
|
+
// parent collapses intermediate directory links (so containment cannot be
|
|
393
|
+
// dodged) while leaving the final component exactly as the operator named
|
|
394
|
+
// it, for the kernel to reject. A test asserts this.
|
|
395
|
+
return join(realpathSync(dirname(c)), basename(c));
|
|
396
|
+
}
|
|
397
|
+
catch {
|
|
398
|
+
// Parent does not resolve (dangling or removed). Return the literal path so
|
|
399
|
+
// checkRoleguideMarkers reports the real reason rather than silently
|
|
400
|
+
// falling through to the next candidate.
|
|
401
|
+
return c;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return null;
|
|
405
|
+
}
|
|
406
|
+
function enforceBehavioralContract(roleguide, slug, projectRoot, worktreeDir, allowMissing) {
|
|
407
|
+
const roots = allowedRoleguideRoots(projectRoot, worktreeDir);
|
|
408
|
+
const roleguideAbs = resolveRoleguidePath(roleguide, projectRoot, roots);
|
|
409
|
+
// A relative argument that would climb out of EVERY allowed root is rejected on
|
|
410
|
+
// the ARGUMENT, before the file is even looked for. Otherwise
|
|
411
|
+
// `--roleguide ../../../x.md` naming a file that does not exist is reported as
|
|
412
|
+
// merely "missing" — which `--allow-missing-behavioral-markers` then waves
|
|
413
|
+
// through, telling the operator nothing about the malformed path. Containment
|
|
414
|
+
// failures are never overridable, so classifying it correctly here also keeps
|
|
415
|
+
// the override from applying.
|
|
416
|
+
const argEscapes = !roleguide.startsWith('/') &&
|
|
417
|
+
roots.every((r) => {
|
|
418
|
+
const rel = relative(r, join(r, roleguide));
|
|
419
|
+
return rel.startsWith('..') || isAbsolute(rel);
|
|
420
|
+
});
|
|
421
|
+
const result = argEscapes
|
|
422
|
+
? {
|
|
423
|
+
ok: false,
|
|
424
|
+
content: null,
|
|
425
|
+
raw: null,
|
|
426
|
+
problem: 'roleguide-path-escapes-root',
|
|
427
|
+
detail: `"${roleguide}" resolves outside every allowed location ` +
|
|
428
|
+
`(${roots.join(', ')}) — a roleguide path may not climb out of the project`,
|
|
429
|
+
}
|
|
430
|
+
: roleguideAbs
|
|
431
|
+
? checkRoleguideMarkers(roleguideAbs, { allowedRoots: roots, label: roleguide })
|
|
432
|
+
: {
|
|
433
|
+
ok: false,
|
|
434
|
+
content: null,
|
|
435
|
+
raw: null,
|
|
436
|
+
problem: 'roleguide-missing',
|
|
437
|
+
detail: `roleguide not found at ${roleguide} (looked under: ${roots.join(', ')})`,
|
|
438
|
+
};
|
|
439
|
+
/**
|
|
440
|
+
* The root `roleguideAbs` actually sits under — the MOST SPECIFIC one, since
|
|
441
|
+
* `roots` is sorted deepest-first. Null when it sits under none.
|
|
442
|
+
*/
|
|
443
|
+
const owningRoot = roleguideAbs
|
|
444
|
+
? roots.find((r) => {
|
|
445
|
+
try {
|
|
446
|
+
return pathIsInside(roleguideAbs, realpathSync(r));
|
|
447
|
+
}
|
|
448
|
+
catch {
|
|
449
|
+
return false;
|
|
450
|
+
}
|
|
451
|
+
}) ?? null
|
|
452
|
+
: null;
|
|
453
|
+
const validated = !argEscapes && roleguideAbs && owningRoot
|
|
454
|
+
? { absPath: roleguideAbs, root: owningRoot, raw: result.raw }
|
|
455
|
+
: null;
|
|
456
|
+
if (result.ok) {
|
|
457
|
+
logSuccess(`Roleguide has a behavioral block (${result.content.split('\n').length} lines)`);
|
|
458
|
+
return validated;
|
|
459
|
+
}
|
|
460
|
+
// A path/containment failure is NOT overridable. The flag exists to roll back
|
|
461
|
+
// the MARKER requirement, not to authorise reading a roleguide from outside the
|
|
462
|
+
// project root or through a symlink — that is a different risk (arbitrary text
|
|
463
|
+
// into every-turn model context) with a different owner, and an override that
|
|
464
|
+
// quietly covers both is how a narrow escape hatch becomes a wide one.
|
|
465
|
+
// Every problem class that is a PATH/CONTAINMENT failure rather than a MARKER
|
|
466
|
+
// failure. The override rolls back the marker requirement only; it must never
|
|
467
|
+
// authorise reading from an unapproved location.
|
|
468
|
+
//
|
|
469
|
+
// `roleguide-hard-link` was missing here (#4541 review round 5). It was not
|
|
470
|
+
// exploitable — that branch returns `raw: null`, so nothing is written, and
|
|
471
|
+
// writeClaudeLocal re-rejects — but a hard link is the same risk class as a
|
|
472
|
+
// symlink by this module's own reasoning, and a misclassification sitting on a
|
|
473
|
+
// security-decision set is exactly what becomes exploitable two refactors later.
|
|
474
|
+
const PATH_PROBLEMS = new Set([
|
|
475
|
+
'roleguide-path-escapes-root',
|
|
476
|
+
'roleguide-symlink',
|
|
477
|
+
'roleguide-hard-link',
|
|
478
|
+
'roleguide-not-regular-file',
|
|
479
|
+
]);
|
|
480
|
+
const isPathProblem = result.problem !== null && PATH_PROBLEMS.has(result.problem);
|
|
481
|
+
if (allowMissing && !isPathProblem) {
|
|
482
|
+
logWarning(`Behavioral block MISSING for "${slug}" — provisioning anyway because ` +
|
|
483
|
+
`--allow-missing-behavioral-markers was passed. This team will run with NO ` +
|
|
484
|
+
`every-turn behavioral reinforcement. ${describeBehavioralProblem(result)}`, 'behavioral-contract-overridden');
|
|
485
|
+
return validated;
|
|
486
|
+
}
|
|
487
|
+
// Headline names the ACTUAL problem class. Saying "no behavioral block" for a
|
|
488
|
+
// file that has a perfectly good block but sits outside the project root sends
|
|
489
|
+
// the operator to add markers that are already there.
|
|
490
|
+
const headline = isPathProblem
|
|
491
|
+
? 'Provisioning REFUSED — roleguide is not in an allowed location.'
|
|
492
|
+
: 'Provisioning REFUSED — roleguide has no behavioral block.';
|
|
493
|
+
throw new BehavioralContractError([
|
|
494
|
+
'',
|
|
495
|
+
chalk.red.bold(headline),
|
|
496
|
+
'',
|
|
497
|
+
` ${chalk.bold('Team:')} ${slug}`,
|
|
498
|
+
` ${chalk.bold('Roleguide:')} ${roleguide}`,
|
|
499
|
+
` ${chalk.bold('Problem:')} ${result.detail}`,
|
|
500
|
+
'',
|
|
501
|
+
...(isPathProblem
|
|
502
|
+
? [
|
|
503
|
+
chalk.dim(' The roleguide is read into this team\'s CLAUDE.local.md, which is re-injected'),
|
|
504
|
+
chalk.dim(' into model context on every conversation turn. It must therefore be a regular'),
|
|
505
|
+
chalk.dim(' file committed inside the project — not a symlink, and not an out-of-tree path,'),
|
|
506
|
+
chalk.dim(' whose content would never appear in a diff or in review (#4541).'),
|
|
507
|
+
'',
|
|
508
|
+
` ${chalk.bold('Fix:')} move the roleguide into the project and pass a path inside it.`,
|
|
509
|
+
chalk.dim(' --allow-missing-behavioral-markers does NOT override this; it only rolls back'),
|
|
510
|
+
chalk.dim(' the marker requirement.'),
|
|
511
|
+
'',
|
|
512
|
+
]
|
|
513
|
+
: [
|
|
514
|
+
chalk.dim(' Every team\'s CLAUDE.local.md — the file re-injected on every conversation'),
|
|
515
|
+
chalk.dim(' turn — is generated from the roleguide content between the two markers.'),
|
|
516
|
+
chalk.dim(' Without a non-empty block this team would run with isolation-only context:'),
|
|
517
|
+
chalk.dim(' no prior-art gate, no decision authority, no delegation limits (#4541).'),
|
|
518
|
+
'',
|
|
519
|
+
` ${chalk.bold('Fix:')} add these markers around the behavioral sections of ${roleguide}`,
|
|
520
|
+
` ${chalk.cyan(BEHAVIORAL_START_MARKER)}`,
|
|
521
|
+
chalk.dim(' ...decision authority, prior-art gate, delegation limits, stop conditions...'),
|
|
522
|
+
` ${chalk.cyan(BEHAVIORAL_END_MARKER)}`,
|
|
523
|
+
` then re-run: ${chalk.cyan(`mx-agent provision --roleguide ${roleguide} --name ${slug}`)}`,
|
|
524
|
+
'',
|
|
525
|
+
chalk.dim(' Documented rollback override only: --allow-missing-behavioral-markers'),
|
|
526
|
+
'',
|
|
527
|
+
]),
|
|
528
|
+
].join('\n'));
|
|
529
|
+
}
|
|
27
530
|
export async function runCreate(options) {
|
|
28
531
|
const { roleguide } = options;
|
|
29
532
|
// Resolve team slug
|
|
@@ -64,6 +567,11 @@ export async function runCreate(options) {
|
|
|
64
567
|
console.log(` ${chalk.bold('Roleguide:')} ${roleguide}`);
|
|
65
568
|
console.log(` ${chalk.bold('Root:')} ${projectRoot}`);
|
|
66
569
|
console.log();
|
|
570
|
+
// ── 0. Behavioral-block contract (#4541) ───────────────────────────
|
|
571
|
+
// Runs FIRST, before slot allocation / worktree / memories / catalog, so a
|
|
572
|
+
// refusal leaves no partial team behind. Throws BehavioralContractError.
|
|
573
|
+
// The returned path is the SINGLE resolution used by steps 6 and 6b below.
|
|
574
|
+
const contract = enforceBehavioralContract(roleguide, slug, projectRoot, cfg.worktreeDir, options.allowMissingBehavioralMarkers === true);
|
|
67
575
|
// ── 1. Slot allocation ─────────────────────────────────────────────
|
|
68
576
|
let slot;
|
|
69
577
|
try {
|
|
@@ -113,6 +621,11 @@ export async function runCreate(options) {
|
|
|
113
621
|
syncClaudeConfig(worktreePath, cfg);
|
|
114
622
|
deployClaudeMd(projectRoot, worktreePath, cfg);
|
|
115
623
|
// ── 6. Generate CLAUDE.local.md ────────────────────────────────────
|
|
624
|
+
// The behavioral block comes from the SAME absolute path step 0 validated, not
|
|
625
|
+
// from a catalog lookup: the catalog entry is not written until step 8, and the
|
|
626
|
+
// operator's roleguide may live in the caller's cwd rather than projectRoot
|
|
627
|
+
// (#4541 security review). Without the override this printed "Behavioral block
|
|
628
|
+
// MISSING" on every successful provision.
|
|
116
629
|
const currentBranch = getCurrentBranch(worktreePath) || branch;
|
|
117
630
|
writeClaudeLocal({
|
|
118
631
|
projectRoot,
|
|
@@ -122,26 +635,71 @@ export async function runCreate(options) {
|
|
|
122
635
|
slot,
|
|
123
636
|
projectSlug: cfg.projectSlug,
|
|
124
637
|
teamSlug: slug,
|
|
638
|
+
behavioralOverride: contract
|
|
639
|
+
? {
|
|
640
|
+
roleguideAbsPath: contract.absPath,
|
|
641
|
+
roleguideRelPath: roleguide,
|
|
642
|
+
displayName,
|
|
643
|
+
allowedRoots: [contract.root],
|
|
644
|
+
// Same bytes the contract validated and step 6b copies — one read.
|
|
645
|
+
raw: contract.raw,
|
|
646
|
+
}
|
|
647
|
+
: undefined,
|
|
125
648
|
});
|
|
126
649
|
// ── 6b. Ensure roleguide exists in the new worktree ───────────────
|
|
127
|
-
// When the team-builder creates a roleguide in its own worktree and
|
|
128
|
-
//
|
|
129
|
-
//
|
|
130
|
-
//
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
if (
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
650
|
+
// When the team-builder creates a roleguide in its own worktree and then runs
|
|
651
|
+
// `mx-agent provision`, the new worktree (based on origin/main) won't have the
|
|
652
|
+
// roleguide yet, so it is copied in.
|
|
653
|
+
//
|
|
654
|
+
// FILESYSTEM SINK — every component traces to a validated value:
|
|
655
|
+
// source bytes : contract.raw (read from the validated descriptor)
|
|
656
|
+
// source path : contract.absPath (validated, contained by step 0)
|
|
657
|
+
// source root : contract.root (the allowed root it was found under)
|
|
658
|
+
// destination : reanchorContained(...) (derived from the above, never from
|
|
659
|
+
// the operator's `roleguide` string)
|
|
660
|
+
// mode : 0644, fixed (never inherited from the source)
|
|
661
|
+
// The raw operator string is used ONLY for human-readable messages below.
|
|
662
|
+
if (contract) {
|
|
663
|
+
const anchored = reanchorContained(contract.root, contract.absPath, worktreePath);
|
|
664
|
+
// The sink accepts a ROLEGUIDE, so it says so. Containment alone would let
|
|
665
|
+
// `--roleguide .claude/agents/x.md` (on a file carrying the two markers) be
|
|
666
|
+
// written to `<newworktree>/.claude/agents/x.md` — contained to the team being
|
|
667
|
+
// provisioned, and operator-supplied, but the sink has no business writing
|
|
668
|
+
// anywhere except the configured roleguides directory (#4541 review round 5).
|
|
669
|
+
const roleguidePrefix = cfg.roleguidesDir.endsWith('/')
|
|
670
|
+
? cfg.roleguidesDir
|
|
671
|
+
: `${cfg.roleguidesDir}/`;
|
|
672
|
+
const relOk = anchored.ok &&
|
|
673
|
+
anchored.rel.startsWith(roleguidePrefix) &&
|
|
674
|
+
anchored.rel.endsWith('.md');
|
|
675
|
+
if (anchored.ok && !relOk) {
|
|
676
|
+
logWarning(`Refusing to copy ${anchored.rel} into the new worktree: a roleguide must live ` +
|
|
677
|
+
`under ${roleguidePrefix} and end in .md. The team will not start until the ` +
|
|
678
|
+
`roleguide is on ${cfg.baseBranch}.`);
|
|
679
|
+
}
|
|
680
|
+
else if (!anchored.ok) {
|
|
681
|
+
logWarning(`Refusing to copy the roleguide into the new worktree: ${anchored.detail}. ` +
|
|
682
|
+
`The team will not start until the roleguide is on ${cfg.baseBranch}.`);
|
|
683
|
+
}
|
|
684
|
+
else if (existsSync(anchored.dest)) {
|
|
685
|
+
logDim('Roleguide already present in the new worktree');
|
|
686
|
+
}
|
|
687
|
+
else if (contract.raw === null) {
|
|
688
|
+
logWarning(`Roleguide at ${roleguide} could not be read — the new team will not be able ` +
|
|
689
|
+
`to start until this file exists in the worktree`);
|
|
690
|
+
}
|
|
691
|
+
else {
|
|
692
|
+
const realWorktree = realpathSync(worktreePath);
|
|
693
|
+
const written = writeContained(anchored.dest, realWorktree, contract.raw);
|
|
694
|
+
if (written.ok) {
|
|
695
|
+
logSuccess(`Roleguide copied to new worktree as ${anchored.rel} (not yet on ${cfg.baseBranch})`);
|
|
696
|
+
}
|
|
697
|
+
else {
|
|
698
|
+
logWarning(`Could not copy the roleguide into the new worktree: ${written.detail}`);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
143
701
|
}
|
|
144
|
-
else
|
|
702
|
+
else {
|
|
145
703
|
logWarning(`Roleguide not found at ${roleguide} — the new team will not be able to start until this file exists`);
|
|
146
704
|
}
|
|
147
705
|
// ── 7. Initialise named memories via mx ───────────────────────────
|
|
@@ -188,11 +746,28 @@ export async function runCreate(options) {
|
|
|
188
746
|
}, cfg.teamsDir);
|
|
189
747
|
logSuccess(`mx-agent-system/teams/${slug}.md`);
|
|
190
748
|
// Also copy the catalog entry to the new worktree so it's visible there.
|
|
749
|
+
//
|
|
750
|
+
// FILESYSTEM SINK — same shape as 6b, same containment. Lower risk (the path
|
|
751
|
+
// is built from in-repo reviewed config plus a slug already validated against
|
|
752
|
+
// SLUG_RE), but identical in form, and a second uncontained copy is not left
|
|
753
|
+
// behind just because its inputs look trustworthy today.
|
|
754
|
+
// source root : projectRoot
|
|
755
|
+
// source path : catalogInSource (projectRoot + configured teamsDir + validated slug)
|
|
756
|
+
// destination : reanchorContained(...)
|
|
757
|
+
// mode : 0644, fixed
|
|
191
758
|
const catalogInSource = join(projectRoot, cfg.teamsDir, `${slug}.md`);
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
759
|
+
if (existsSync(catalogInSource)) {
|
|
760
|
+
const anchoredCatalog = reanchorContained(projectRoot, catalogInSource, worktreePath);
|
|
761
|
+
if (!anchoredCatalog.ok) {
|
|
762
|
+
logWarning(`Could not copy the catalog entry into the new worktree: ${anchoredCatalog.detail}`);
|
|
763
|
+
}
|
|
764
|
+
else if (!existsSync(anchoredCatalog.dest)) {
|
|
765
|
+
const bytes = readFileSync(catalogInSource, 'utf-8');
|
|
766
|
+
const written = writeContained(anchoredCatalog.dest, realpathSync(worktreePath), bytes);
|
|
767
|
+
if (!written.ok) {
|
|
768
|
+
logWarning(`Could not copy the catalog entry into the new worktree: ${written.detail}`);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
196
771
|
}
|
|
197
772
|
}
|
|
198
773
|
catch (err) {
|
|
@@ -222,4 +797,12 @@ export async function runCreate(options) {
|
|
|
222
797
|
console.log(` Check status: ${chalk.cyan(`mx-agent status ${slug}`)}`);
|
|
223
798
|
console.log();
|
|
224
799
|
}
|
|
800
|
+
/**
|
|
801
|
+
* Test-only surface for the two filesystem-containment helpers.
|
|
802
|
+
*
|
|
803
|
+
* Exported so the containment property can be asserted against the REAL
|
|
804
|
+
* filesystem (was a byte written outside the destination root?) rather than
|
|
805
|
+
* inferred from a refusal message. Not part of the command API.
|
|
806
|
+
*/
|
|
807
|
+
export const __testing = { reanchorContained, writeContained, allowedRoleguideRoots };
|
|
225
808
|
//# sourceMappingURL=create.js.map
|