@memnexus-ai/mx-agent-cli 0.1.241 → 0.1.243
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__/agents-md-canonicalization.test.d.ts +11 -8
- package/dist/__tests__/agents-md-canonicalization.test.d.ts.map +1 -1
- package/dist/__tests__/agents-md-canonicalization.test.js +60 -19
- package/dist/__tests__/agents-md-canonicalization.test.js.map +1 -1
- package/dist/__tests__/behavioral-git-read.test.d.ts +21 -0
- package/dist/__tests__/behavioral-git-read.test.d.ts.map +1 -0
- package/dist/__tests__/behavioral-git-read.test.js +955 -0
- package/dist/__tests__/behavioral-git-read.test.js.map +1 -0
- package/dist/__tests__/event-shipper.test.d.ts +16 -0
- package/dist/__tests__/event-shipper.test.d.ts.map +1 -0
- package/dist/__tests__/event-shipper.test.js +287 -0
- package/dist/__tests__/event-shipper.test.js.map +1 -0
- package/dist/__tests__/shim-deploy-safety.test.d.ts +24 -0
- package/dist/__tests__/shim-deploy-safety.test.d.ts.map +1 -0
- package/dist/__tests__/shim-deploy-safety.test.js +174 -0
- package/dist/__tests__/shim-deploy-safety.test.js.map +1 -0
- package/dist/__tests__/start-report-integration.test.js +4 -0
- package/dist/__tests__/start-report-integration.test.js.map +1 -1
- package/dist/__tests__/template-budget.test.js +56 -4
- package/dist/__tests__/template-budget.test.js.map +1 -1
- package/dist/agent-config/CLAUDE.md.template +8 -152
- package/dist/commands/start.d.ts +22 -0
- package/dist/commands/start.d.ts.map +1 -1
- package/dist/commands/start.js +44 -21
- package/dist/commands/start.js.map +1 -1
- package/dist/commands/sync.d.ts.map +1 -1
- package/dist/commands/sync.js +9 -5
- package/dist/commands/sync.js.map +1 -1
- package/dist/lib/behavioral-injection.d.ts +190 -13
- package/dist/lib/behavioral-injection.d.ts.map +1 -1
- package/dist/lib/behavioral-injection.js +653 -37
- package/dist/lib/behavioral-injection.js.map +1 -1
- package/dist/lib/claude.d.ts +77 -1
- package/dist/lib/claude.d.ts.map +1 -1
- package/dist/lib/claude.js +281 -13
- package/dist/lib/claude.js.map +1 -1
- package/dist/lib/startup-shipper.d.ts +108 -20
- package/dist/lib/startup-shipper.d.ts.map +1 -1
- package/dist/lib/startup-shipper.js +133 -29
- package/dist/lib/startup-shipper.js.map +1 -1
- package/package.json +1 -1
|
@@ -25,21 +25,183 @@
|
|
|
25
25
|
* hooks / settings.json / agent-config conflicts, and this is not that), but
|
|
26
26
|
* the degradation is named by team and surfaced where an operator reads it.
|
|
27
27
|
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
28
|
+
* A third control now exists and this comment used to deny it: the pull-request
|
|
29
|
+
* gate `.github/workflows/roleguide-markers-check.yml` runs
|
|
30
|
+
* `dev-tools/scripts/validate-roleguide-behavioral-markers.sh` on every PR that
|
|
31
|
+
* touches a roleguide. What was descoped was the PRE-PUSH form of that gate
|
|
32
|
+
* (wiring the script into ci-validate-hook.sh), after three security review
|
|
33
|
+
* rounds in which its fixes kept producing new findings. So coverage is enforced
|
|
34
|
+
* at merge for roleguide changes, and at session start per team by consumer (2);
|
|
35
|
+
* what neither catches is a block that decays between merges without the file
|
|
36
|
+
* being touched. Red Team's shared `behavioral-base.md` refactor remains the
|
|
37
|
+
* change that would make coverage a build guarantee.
|
|
38
|
+
*
|
|
39
|
+
* The bash gate duplicates the marker rules below. It is currently LAXER than
|
|
40
|
+
* this module — it matches markers as substrings where this file requires a
|
|
41
|
+
* marker to own its line — so a roleguide can pass the gate and be rejected
|
|
42
|
+
* here. Stricter-at-runtime fails safe (the operator is warned), but the two
|
|
43
|
+
* should be reconciled; tracked as a follow-up on #4707. If you change the
|
|
44
|
+
* marker rules here, change them in that script too.
|
|
45
|
+
*
|
|
46
|
+
* ── #4707: WHERE THE BYTES COME FROM ─────────────────────────────────────────
|
|
47
|
+
*
|
|
48
|
+
* The presence check above was never the whole failure. `mx-agent start` resolved
|
|
49
|
+
* the team catalog file and the roleguide from `projectRoot` — `/workspace`, the
|
|
50
|
+
* MAIN REPO working tree, never the worktree and never a git ref. That checkout
|
|
51
|
+
* drifts: on 2026-07-30 it was 82 commits behind `origin/main`, so the markers
|
|
52
|
+
* added to `eval-leader-v3.md` by #4521 four days earlier had never been read.
|
|
53
|
+
* Eval's sessions shipped an isolation-only CLAUDE.local.md while the same
|
|
54
|
+
* startup sequence printed "Agent config generated from … (origin/main)". One
|
|
55
|
+
* source of truth, two answers.
|
|
56
|
+
*
|
|
57
|
+
* `resolveBehavioralInjection` now reads BOTH files from
|
|
58
|
+
* `git show <remote>/<baseBranch>:<path>` — the same source `syncClaudeConfig`
|
|
59
|
+
* already uses — and falls back to the local working tree ONLY when git cannot
|
|
60
|
+
* serve the bytes (no remote, offline, ref or path absent, e.g. a team whose
|
|
61
|
+
* catalog entry has not merged yet). The fallback is never silent: the caller
|
|
62
|
+
* warns with `behavioral-git-read-fallback` and names the reason.
|
|
63
|
+
*
|
|
64
|
+
* WHAT GIT-FIRST BUYS, STATED EXACTLY. It buys STALENESS resistance and
|
|
65
|
+
* REVIEWABILITY: the bytes injected into every turn are bytes that passed pull
|
|
66
|
+
* request review and CODEOWNERS on the base branch, and they cannot silently be
|
|
67
|
+
* an old copy of a file that was fixed days ago. It does NOT buy tamper
|
|
68
|
+
* resistance against a local writer, and no control should be built on the
|
|
69
|
+
* assumption that it does — anyone who can write the worktree can
|
|
70
|
+
* `git update-ref refs/remotes/origin/<branch>`, point `baseBranch` somewhere
|
|
71
|
+
* else, or simply rewrite CLAUDE.local.md after it is generated. Same reasoning
|
|
72
|
+
* the repo already applies to `git-mutation-guard.sh`: a guardrail against
|
|
73
|
+
* accident and drift, bypassable by design, never an access control.
|
|
74
|
+
*
|
|
75
|
+
* The git path carries its own symlink defense rather than inheriting the ~200
|
|
76
|
+
* lines below: a git tree entry records the mode, so a symlink is mode 120000
|
|
77
|
+
* with the target as blob content, and `readTreeEntry` rejects anything that is
|
|
78
|
+
* not a regular blob (100644/100755). A tree entry cannot name a path outside
|
|
79
|
+
* the repository at all, which is the property the local path spends realpath
|
|
80
|
+
* and O_NOFOLLOW establishing.
|
|
81
|
+
*
|
|
82
|
+
* RESIDUAL, precisely: the mode is read by `ls-tree` and the bytes by a separate
|
|
83
|
+
* `git show <ref>:<path>`, so the two calls re-resolve the path independently. A
|
|
84
|
+
* ref moved between them yields a mode check on one blob and a read of another.
|
|
85
|
+
* Closing it means resolving the object id once and reading it with
|
|
86
|
+
* `git cat-file blob <oid>`; filed as a follow-up on #4707 rather than fixed
|
|
87
|
+
* here. Scope of the window: it needs a writer who can move the remote-tracking
|
|
88
|
+
* ref mid-start, which is the same actor the paragraph above says this design
|
|
89
|
+
* does not defend against.
|
|
90
|
+
*
|
|
91
|
+
* The local-path defenses stay because `mx-agent create` still validates a
|
|
92
|
+
* roleguide on disk before it is ever committed.
|
|
93
|
+
*
|
|
94
|
+
* Content, not presence (#4707 item 3). mcp is the proof that a block header
|
|
95
|
+
* guarantees nothing: 57 lines, 0 of the 4 elements a behavioral block exists to
|
|
96
|
+
* carry. `checkBehavioralCompleteness` looks for those four and names the ones it
|
|
97
|
+
* did not find; `mx-agent start` runs it against the CLAUDE.local.md it just
|
|
98
|
+
* WROTE, so it reads the delivered artifact rather than the file we edited.
|
|
99
|
+
*
|
|
100
|
+
* Say what that check is: a KEYWORD MATCH, reported as "matched by keyword", not
|
|
101
|
+
* "verified". It cannot tell a rule from its negation and makes no claim to. The
|
|
102
|
+
* integrity check in `writeClaudeLocalWithBehavioralSelfHeal` — delivered bytes
|
|
103
|
+
* equal resolved bytes, exactly one behavioral header — IS a verification, and
|
|
104
|
+
* the two must not be read as one thing (Codex differential review, finding 2).
|
|
38
105
|
*/
|
|
39
106
|
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync, } from 'fs';
|
|
40
107
|
import { basename, dirname, join, sep } from 'path';
|
|
108
|
+
import { spawnSync } from 'child_process';
|
|
41
109
|
export const BEHAVIORAL_START_MARKER = '<!-- behavioral-start -->';
|
|
42
110
|
export const BEHAVIORAL_END_MARKER = '<!-- behavioral-end -->';
|
|
111
|
+
// ── Size limits (#4707 security review, SF-2) ────────────────────────────
|
|
112
|
+
//
|
|
113
|
+
// TWO LIMITS, AND THE ORDER MATTERS. A size problem must never be reportable as
|
|
114
|
+
// "git could not serve this", because that answer routes to the LOCAL FALLBACK —
|
|
115
|
+
// the stale working tree this change exists to stop reading. An oversize
|
|
116
|
+
// roleguide is a REJECTION with a named cause, not an availability failure.
|
|
117
|
+
/**
|
|
118
|
+
* Largest roleguide FILE either path will read. A roleguide is a document a
|
|
119
|
+
* person maintains; the largest on origin/main is under 60 KB. One megabyte is
|
|
120
|
+
* two orders of magnitude of headroom and still bounds `spawnSync`'s buffer, the
|
|
121
|
+
* fd read, and the time spent on either.
|
|
122
|
+
*/
|
|
123
|
+
export const MAX_ROLEGUIDE_BYTES = 1024 * 1024;
|
|
124
|
+
/**
|
|
125
|
+
* Largest behavioral block that will be injected. This is the number that
|
|
126
|
+
* matters: these bytes are re-sent on EVERY conversation turn, so an oversize
|
|
127
|
+
* block is a token-cost and context-eviction problem for the team that gets it,
|
|
128
|
+
* not merely a parsing curiosity. 128 KiB against a real case of 55 lines.
|
|
129
|
+
*/
|
|
130
|
+
export const MAX_BEHAVIORAL_BLOCK_BYTES = 128 * 1024;
|
|
131
|
+
/**
|
|
132
|
+
* C0 control characters other than tab, newline and carriage return, plus DEL.
|
|
133
|
+
*
|
|
134
|
+
* These bytes reach two sinks verbatim: per-turn model context, and the
|
|
135
|
+
* operator's terminal through the startup warnings. ESC (0x1B) in the second
|
|
136
|
+
* sink is terminal escape injection — a roleguide could repaint or clear the
|
|
137
|
+
* very warning that reports it. Markdown needs none of them, so their presence
|
|
138
|
+
* is a defect in the file, and this module names defects rather than silently
|
|
139
|
+
* repairing them (a stripped block would differ from the reviewed source while
|
|
140
|
+
* reporting success).
|
|
141
|
+
*/
|
|
142
|
+
const CONTROL_CHARS = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/;
|
|
143
|
+
/**
|
|
144
|
+
* The display name from the team catalog, or the slug when it is unusable.
|
|
145
|
+
*
|
|
146
|
+
* The display name is not decoration: it is interpolated into the
|
|
147
|
+
* `# <Display> — Behavioral Checks` header of CLAUDE.local.md and into the
|
|
148
|
+
* warnings printed to the operator's terminal. Control characters there are
|
|
149
|
+
* terminal escape injection with a straight path to both sinks. Unlike block
|
|
150
|
+
* CONTENT — where a defect is named and nothing is injected — falling back to
|
|
151
|
+
* the slug is the right trade for a cosmetic field: the session keeps its
|
|
152
|
+
* reinforcement and loses only a label. Length is capped for the same reason a
|
|
153
|
+
* header is one line.
|
|
154
|
+
*/
|
|
155
|
+
function safeDisplayName(parsed, slug) {
|
|
156
|
+
if (!parsed)
|
|
157
|
+
return slug;
|
|
158
|
+
if (CONTROL_CHARS.test(parsed))
|
|
159
|
+
return slug;
|
|
160
|
+
if (parsed.length > 120)
|
|
161
|
+
return slug;
|
|
162
|
+
return parsed;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Make an untrusted value safe to put in a message a human will read.
|
|
166
|
+
*
|
|
167
|
+
* REJECTING A VALUE IS NOT THE SAME AS NOT PRINTING IT (Codex differential
|
|
168
|
+
* review, finding 1). Every check in this module that refuses an unsafe slug or
|
|
169
|
+
* path then quotes that value back in `detail`, and `writeClaudeLocal` prints
|
|
170
|
+
* `detail` through `logWarning` to the operator's terminal. So
|
|
171
|
+
* `CLAUDE_TEAM_NAME=$'bad\x1b[2J'` was refused as a slug and its escape sequence
|
|
172
|
+
* was emitted anyway — the refusal path became the injection path. This repo has
|
|
173
|
+
* the identical defect on record once already: KI-STARTUPREPORT-PRINTOUT-
|
|
174
|
+
* UNSANITIZED, sanitized at the store and unsanitized at the print.
|
|
175
|
+
*
|
|
176
|
+
* SANITIZE AT FORMATTING, NOT AT THE SINK. The print sink (`logWarning`) wraps
|
|
177
|
+
* its argument in chalk, which emits ESC itself, so stripping there would strip
|
|
178
|
+
* our own colour codes and would not be reachable from the non-printing
|
|
179
|
+
* consumers of `detail` anyway. Sanitizing where an untrusted value enters
|
|
180
|
+
* message text keeps the guarantee local to the value: any future call site that
|
|
181
|
+
* interpolates a slug or a path goes through this function or repeats the bug.
|
|
182
|
+
*
|
|
183
|
+
* Removed: C0 (including ESC, so no CSI/OSC sequence can be assembled), DEL, and
|
|
184
|
+
* C1 (0x80-0x9F, which some terminals decode as escape sequences in their own
|
|
185
|
+
* right). Each is replaced by U+FFFD rather than dropped, so a value that was
|
|
186
|
+
* censored looks censored instead of looking like a shorter legitimate name.
|
|
187
|
+
* Length is capped because an unbounded value in a one-line warning is its own
|
|
188
|
+
* way of hiding the rest of the message.
|
|
189
|
+
*/
|
|
190
|
+
export function sanitizeForMessage(value, maxLength = 200) {
|
|
191
|
+
const stripped = value.replace(/[\x00-\x1F\x7F-\x9F]/g, '�');
|
|
192
|
+
return stripped.length > maxLength
|
|
193
|
+
? `${stripped.slice(0, maxLength)}… (${stripped.length} chars)`
|
|
194
|
+
: stripped;
|
|
195
|
+
}
|
|
196
|
+
/** Human-readable position of the first control character, for the message. */
|
|
197
|
+
function describeControlChar(text) {
|
|
198
|
+
const idx = text.search(CONTROL_CHARS);
|
|
199
|
+
if (idx === -1)
|
|
200
|
+
return '';
|
|
201
|
+
const code = text.charCodeAt(idx);
|
|
202
|
+
const line = text.slice(0, idx).split('\n').length;
|
|
203
|
+
return `0x${code.toString(16).padStart(2, '0').toUpperCase()} at line ${line}`;
|
|
204
|
+
}
|
|
43
205
|
/**
|
|
44
206
|
* True when `candidate` is `root` itself or lies beneath it.
|
|
45
207
|
*
|
|
@@ -93,6 +255,34 @@ function isSymlink(absPath) {
|
|
|
93
255
|
return false;
|
|
94
256
|
}
|
|
95
257
|
}
|
|
258
|
+
/**
|
|
259
|
+
* Character offsets of every line whose ENTIRE trimmed content is `marker`.
|
|
260
|
+
*
|
|
261
|
+
* LINE-ANCHORED ON PURPOSE (#4707). A substring search counts prose: the
|
|
262
|
+
* team-builder roleguide names both markers inside sentences, backticks and a
|
|
263
|
+
* table row, so `origin/main` reads 4 starts and 3 ends for a file whose actual
|
|
264
|
+
* block is one correct pair on lines 15 and 27. Counting those mentions as
|
|
265
|
+
* markers would either mis-bound the block or reject a valid roleguide, and both
|
|
266
|
+
* are worse than the bug being fixed. A delimiter is a delimiter only when it
|
|
267
|
+
* owns its line — that is how every roleguide in the repo writes it, verified
|
|
268
|
+
* across all 17 on `origin/main`.
|
|
269
|
+
*
|
|
270
|
+
* NOTE FOR THE BASH GATE. `dev-tools/scripts/validate-roleguide-behavioral-markers.sh`
|
|
271
|
+
* still uses `grep -F`, so it is LAXER than this parser: a roleguide with only
|
|
272
|
+
* inline mentions passes the pull-request gate and is then rejected here, loudly,
|
|
273
|
+
* at session start. Stricter-at-runtime fails safe (the operator is told), but
|
|
274
|
+
* the two should be reconciled — tracked on #4707.
|
|
275
|
+
*/
|
|
276
|
+
function markerLines(text, marker) {
|
|
277
|
+
const hits = [];
|
|
278
|
+
let offset = 0;
|
|
279
|
+
for (const line of text.split('\n')) {
|
|
280
|
+
if (line.trim() === marker)
|
|
281
|
+
hits.push({ start: offset, end: offset + line.length });
|
|
282
|
+
offset += line.length + 1; // +1 for the '\n' consumed by split
|
|
283
|
+
}
|
|
284
|
+
return hits;
|
|
285
|
+
}
|
|
96
286
|
/**
|
|
97
287
|
* Extract the behavioral block from ALREADY-READ bytes. Pure — no filesystem
|
|
98
288
|
* access, so it never re-resolves a path.
|
|
@@ -103,13 +293,16 @@ function isSymlink(absPath) {
|
|
|
103
293
|
* return different content, which would let the roleguide copied into a worktree
|
|
104
294
|
* and the block injected into that team's per-turn context disagree.
|
|
105
295
|
*/
|
|
106
|
-
export function extractMarkerBlock(text,
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
296
|
+
export function extractMarkerBlock(text, rawLabel) {
|
|
297
|
+
// Sanitized ONCE here, so every `detail` this function builds is safe by
|
|
298
|
+
// construction rather than by each author remembering.
|
|
299
|
+
const label = sanitizeForMessage(rawLabel);
|
|
300
|
+
const starts = markerLines(text, BEHAVIORAL_START_MARKER);
|
|
301
|
+
const ends = markerLines(text, BEHAVIORAL_END_MARKER);
|
|
302
|
+
if (starts.length === 0 || ends.length === 0) {
|
|
303
|
+
const missing = starts.length === 0 && ends.length === 0
|
|
111
304
|
? `${BEHAVIORAL_START_MARKER} and ${BEHAVIORAL_END_MARKER}`
|
|
112
|
-
:
|
|
305
|
+
: starts.length === 0
|
|
113
306
|
? BEHAVIORAL_START_MARKER
|
|
114
307
|
: BEHAVIORAL_END_MARKER;
|
|
115
308
|
return {
|
|
@@ -117,19 +310,57 @@ export function extractMarkerBlock(text, label) {
|
|
|
117
310
|
detail: `${label} is missing ${missing}`,
|
|
118
311
|
};
|
|
119
312
|
}
|
|
313
|
+
// REPEATED OR NESTED MARKERS FAIL LOUDLY (#4707). The previous code took
|
|
314
|
+
// `indexOf` of each marker, so a file with two blocks — or a nested pair —
|
|
315
|
+
// silently yielded the FIRST start paired with the FIRST end. That extracts a
|
|
316
|
+
// partial or wrongly-bounded block, reports `ok: true`, and the operator sees
|
|
317
|
+
// nothing at all. Which of several blocks is "the" behavioral block is not a
|
|
318
|
+
// question this parser is entitled to guess: the answer changes what gets
|
|
319
|
+
// injected into every turn of that team's context. Say so and extract nothing.
|
|
320
|
+
if (starts.length > 1 || ends.length > 1) {
|
|
321
|
+
return {
|
|
322
|
+
ok: false, content: null, raw: text, problem: 'markers-repeated',
|
|
323
|
+
detail: `${label} has ${starts.length} ${BEHAVIORAL_START_MARKER} and ` +
|
|
324
|
+
`${ends.length} ${BEHAVIORAL_END_MARKER} lines — exactly one of each is required ` +
|
|
325
|
+
`(repeated or nested markers make the block boundaries ambiguous)`,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
const startIdx = starts[0].start;
|
|
329
|
+
const endIdx = ends[0].start;
|
|
120
330
|
if (endIdx <= startIdx) {
|
|
121
331
|
return {
|
|
122
332
|
ok: false, content: null, raw: text, problem: 'markers-inverted',
|
|
123
333
|
detail: `${label} has ${BEHAVIORAL_END_MARKER} before ${BEHAVIORAL_START_MARKER}`,
|
|
124
334
|
};
|
|
125
335
|
}
|
|
126
|
-
const content = text.slice(
|
|
336
|
+
const content = text.slice(starts[0].end, endIdx).trim();
|
|
127
337
|
if (!content) {
|
|
128
338
|
return {
|
|
129
339
|
ok: false, content: null, raw: text, problem: 'content-empty',
|
|
130
340
|
detail: `${label} has an EMPTY behavioral block (markers present, no content between them)`,
|
|
131
341
|
};
|
|
132
342
|
}
|
|
343
|
+
// SIZE AND BYTE CHECKS APPLY TO BOTH READ PATHS because every caller — git,
|
|
344
|
+
// local, and the provisioning override — funnels through this function. The
|
|
345
|
+
// block is measured in BYTES, not characters: what costs the team on every
|
|
346
|
+
// turn is what goes over the wire.
|
|
347
|
+
const bytes = Buffer.byteLength(content, 'utf-8');
|
|
348
|
+
if (bytes > MAX_BEHAVIORAL_BLOCK_BYTES) {
|
|
349
|
+
return {
|
|
350
|
+
ok: false, content: null, raw: text, problem: 'content-too-large',
|
|
351
|
+
detail: `${label} has a ${Math.round(bytes / 1024)} KiB behavioral block, over the ` +
|
|
352
|
+
`${MAX_BEHAVIORAL_BLOCK_BYTES / 1024} KiB limit — this text is re-sent on EVERY ` +
|
|
353
|
+
`conversation turn, so an oversize block evicts the team's working context`,
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
if (CONTROL_CHARS.test(content)) {
|
|
357
|
+
return {
|
|
358
|
+
ok: false, content: null, raw: text, problem: 'content-control-characters',
|
|
359
|
+
detail: `${label} contains a control character (${describeControlChar(content)}) inside ` +
|
|
360
|
+
`the behavioral block — these bytes reach per-turn model context and the operator's ` +
|
|
361
|
+
`terminal verbatim`,
|
|
362
|
+
};
|
|
363
|
+
}
|
|
133
364
|
return { ok: true, content, raw: text, problem: null, detail: null };
|
|
134
365
|
}
|
|
135
366
|
/**
|
|
@@ -170,7 +401,7 @@ export function extractMarkerBlock(text, label) {
|
|
|
170
401
|
* Do not pass a world-writable directory as an allowed root.
|
|
171
402
|
*/
|
|
172
403
|
export function checkRoleguideMarkers(roleguideAbsPath, opts) {
|
|
173
|
-
const label = opts.label ?? roleguideAbsPath;
|
|
404
|
+
const label = sanitizeForMessage(opts.label ?? roleguideAbsPath);
|
|
174
405
|
if (!opts.allowedRoots || opts.allowedRoots.length === 0) {
|
|
175
406
|
// Fail CLOSED. A caller that forgot its trust boundary must not get an
|
|
176
407
|
// unbounded read.
|
|
@@ -205,14 +436,14 @@ export function checkRoleguideMarkers(roleguideAbsPath, opts) {
|
|
|
205
436
|
catch {
|
|
206
437
|
return {
|
|
207
438
|
ok: false, content: null, raw: null, problem: 'roleguide-missing',
|
|
208
|
-
detail: `roleguide not found at ${label} (directory does not exist)`,
|
|
439
|
+
detail: `roleguide not found at ${label} (directory does not exist)`, // label sanitized above
|
|
209
440
|
};
|
|
210
441
|
}
|
|
211
442
|
if (!roots.some((root) => isInside(realParent, root))) {
|
|
212
443
|
return {
|
|
213
444
|
ok: false, content: null, raw: null, problem: 'roleguide-path-escapes-root',
|
|
214
|
-
detail: `${label} resolves to ${join(realParent, base)}, outside
|
|
215
|
-
`location(s): ${roots.join(', ')}`,
|
|
445
|
+
detail: `${label} resolves to ${sanitizeForMessage(join(realParent, base))}, outside ` +
|
|
446
|
+
`the allowed location(s): ${sanitizeForMessage(roots.join(', '))}`,
|
|
216
447
|
};
|
|
217
448
|
}
|
|
218
449
|
// Single descriptor: O_NOFOLLOW decides link-ness, fstat decides regular-file-ness,
|
|
@@ -267,6 +498,16 @@ export function checkRoleguideMarkers(roleguideAbsPath, opts) {
|
|
|
267
498
|
`through the other link never appear in a diff)`,
|
|
268
499
|
};
|
|
269
500
|
}
|
|
501
|
+
// Bound the read BEFORE it happens, off the same descriptor the bytes come
|
|
502
|
+
// from (#4707 SF-2). Without this the local path is an unbounded
|
|
503
|
+
// readFileSync into memory and, one step later, into per-turn context.
|
|
504
|
+
if (st.size > MAX_ROLEGUIDE_BYTES) {
|
|
505
|
+
return {
|
|
506
|
+
ok: false, content: null, raw: null, problem: 'content-too-large',
|
|
507
|
+
detail: `${label} is ${Math.round(st.size / 1024)} KiB, over the ` +
|
|
508
|
+
`${MAX_ROLEGUIDE_BYTES / 1024} KiB roleguide limit — refusing to read it`,
|
|
509
|
+
};
|
|
510
|
+
}
|
|
270
511
|
text = readFileSync(fd, 'utf-8');
|
|
271
512
|
}
|
|
272
513
|
catch {
|
|
@@ -292,6 +533,10 @@ export function checkRoleguideMarkers(roleguideAbsPath, opts) {
|
|
|
292
533
|
* escape the project root.
|
|
293
534
|
*/
|
|
294
535
|
export function checkBehavioralInjection(projectRoot, teamSlug, teamsDir = 'mx-agent-system/teams') {
|
|
536
|
+
// Sanitized aliases for MESSAGE use only — the raw values still drive the
|
|
537
|
+
// path logic below. Refusing a value and then echoing it are separate
|
|
538
|
+
// decisions, and this module used to get the second one wrong.
|
|
539
|
+
const shownSlug = sanitizeForMessage(teamSlug, 80);
|
|
295
540
|
const base = (extra) => ({
|
|
296
541
|
ok: false, content: null, raw: null, problem: null, detail: null,
|
|
297
542
|
teamSlug, displayName: teamSlug, roleguideRelPath: null,
|
|
@@ -307,7 +552,7 @@ export function checkBehavioralInjection(projectRoot, teamSlug, teamsDir = 'mx-a
|
|
|
307
552
|
catch {
|
|
308
553
|
return base({
|
|
309
554
|
problem: 'team-file-missing',
|
|
310
|
-
detail: `project root ${projectRoot} does not exist`,
|
|
555
|
+
detail: `project root ${sanitizeForMessage(projectRoot)} does not exist`,
|
|
311
556
|
});
|
|
312
557
|
}
|
|
313
558
|
// 1. Team catalog file — lexical containment, then symlink/escape resolution.
|
|
@@ -316,28 +561,28 @@ export function checkBehavioralInjection(projectRoot, teamSlug, teamsDir = 'mx-a
|
|
|
316
561
|
if (!isInside(teamFilePath, teamsBase) || teamFilePath === teamsBase) {
|
|
317
562
|
return base({
|
|
318
563
|
problem: 'invalid-team-slug',
|
|
319
|
-
detail: `invalid team slug "${
|
|
564
|
+
detail: `invalid team slug "${shownSlug}" — path escapes the teams directory`,
|
|
320
565
|
});
|
|
321
566
|
}
|
|
322
567
|
const teamResolved = safeResolve(teamFilePath, realRoot);
|
|
323
568
|
if (teamResolved.kind === 'missing') {
|
|
324
569
|
return base({
|
|
325
570
|
problem: 'team-file-missing',
|
|
326
|
-
detail: `no team catalog file at ${teamsDir}/${
|
|
571
|
+
detail: `no team catalog file at ${teamsDir}/${shownSlug}.md`,
|
|
327
572
|
});
|
|
328
573
|
}
|
|
329
574
|
if (teamResolved.kind === 'symlink') {
|
|
330
575
|
return base({
|
|
331
576
|
problem: 'team-file-symlink',
|
|
332
|
-
detail: `${teamsDir}/${
|
|
333
|
-
`(${teamResolved.real}) — team catalog files must be regular files`,
|
|
577
|
+
detail: `${teamsDir}/${shownSlug}.md resolves through a symbolic link ` +
|
|
578
|
+
`(${sanitizeForMessage(teamResolved.real)}) — team catalog files must be regular files`,
|
|
334
579
|
});
|
|
335
580
|
}
|
|
336
581
|
if (teamResolved.kind === 'escapes') {
|
|
337
582
|
return base({
|
|
338
583
|
problem: 'team-file-escapes-root',
|
|
339
|
-
detail: `${teamsDir}/${
|
|
340
|
-
`(${teamResolved.real})`,
|
|
584
|
+
detail: `${teamsDir}/${shownSlug}.md resolves outside the project root ` +
|
|
585
|
+
`(${sanitizeForMessage(teamResolved.real)})`,
|
|
341
586
|
});
|
|
342
587
|
}
|
|
343
588
|
let teamFileContent;
|
|
@@ -347,21 +592,19 @@ export function checkBehavioralInjection(projectRoot, teamSlug, teamsDir = 'mx-a
|
|
|
347
592
|
catch {
|
|
348
593
|
return base({
|
|
349
594
|
problem: 'team-file-unreadable',
|
|
350
|
-
detail: `could not read team catalog file ${teamsDir}/${
|
|
595
|
+
detail: `could not read team catalog file ${teamsDir}/${shownSlug}.md`,
|
|
351
596
|
});
|
|
352
597
|
}
|
|
353
598
|
// 2. Display name
|
|
354
599
|
const displayNameLine = teamFileContent.split('\n').find((l) => l.startsWith('Display name:'));
|
|
355
|
-
const displayName = displayNameLine
|
|
356
|
-
? displayNameLine.replace('Display name:', '').trim() || teamSlug
|
|
357
|
-
: teamSlug;
|
|
600
|
+
const displayName = safeDisplayName(displayNameLine ? displayNameLine.replace('Display name:', '').trim() : '', teamSlug);
|
|
358
601
|
// 3. Roleguide path — FIRST backticked token on the `Roleguide:` line.
|
|
359
602
|
const roleguideLineRaw = teamFileContent.split('\n').find((l) => l.startsWith('Roleguide:'));
|
|
360
603
|
if (!roleguideLineRaw) {
|
|
361
604
|
return base({
|
|
362
605
|
displayName,
|
|
363
606
|
problem: 'roleguide-line-missing',
|
|
364
|
-
detail: `no 'Roleguide:' line in ${teamsDir}/${
|
|
607
|
+
detail: `no 'Roleguide:' line in ${teamsDir}/${shownSlug}.md`,
|
|
365
608
|
});
|
|
366
609
|
}
|
|
367
610
|
const roleguideMatch = roleguideLineRaw.match(/`([^`]+)`/);
|
|
@@ -369,7 +612,7 @@ export function checkBehavioralInjection(projectRoot, teamSlug, teamsDir = 'mx-a
|
|
|
369
612
|
return base({
|
|
370
613
|
displayName,
|
|
371
614
|
problem: 'roleguide-path-unparseable',
|
|
372
|
-
detail: `could not parse a backticked roleguide path from ${teamsDir}/${
|
|
615
|
+
detail: `could not parse a backticked roleguide path from ${teamsDir}/${shownSlug}.md`,
|
|
373
616
|
});
|
|
374
617
|
}
|
|
375
618
|
const roleguideRelPath = roleguideMatch[1];
|
|
@@ -380,7 +623,7 @@ export function checkBehavioralInjection(projectRoot, teamSlug, teamsDir = 'mx-a
|
|
|
380
623
|
return base({
|
|
381
624
|
displayName, roleguideRelPath,
|
|
382
625
|
problem: 'roleguide-path-escapes-root',
|
|
383
|
-
detail: `roleguide path "${roleguideRelPath}" escapes the project root`,
|
|
626
|
+
detail: `roleguide path "${sanitizeForMessage(roleguideRelPath)}" escapes the project root`,
|
|
384
627
|
});
|
|
385
628
|
}
|
|
386
629
|
const rgResolved = safeResolve(roleguideAbsPath, realRoot);
|
|
@@ -388,7 +631,8 @@ export function checkBehavioralInjection(projectRoot, teamSlug, teamsDir = 'mx-a
|
|
|
388
631
|
return base({
|
|
389
632
|
displayName, roleguideRelPath,
|
|
390
633
|
problem: 'roleguide-symlink',
|
|
391
|
-
detail: `${roleguideRelPath} resolves through a symbolic link
|
|
634
|
+
detail: `${sanitizeForMessage(roleguideRelPath)} resolves through a symbolic link ` +
|
|
635
|
+
`(${sanitizeForMessage(rgResolved.real)}) — ` +
|
|
392
636
|
`roleguides must be regular files (symlinked content never appears in a diff ` +
|
|
393
637
|
`and is invisible to review)`,
|
|
394
638
|
});
|
|
@@ -397,7 +641,8 @@ export function checkBehavioralInjection(projectRoot, teamSlug, teamsDir = 'mx-a
|
|
|
397
641
|
return base({
|
|
398
642
|
displayName, roleguideRelPath,
|
|
399
643
|
problem: 'roleguide-path-escapes-root',
|
|
400
|
-
detail: `${roleguideRelPath} resolves outside the project root
|
|
644
|
+
detail: `${sanitizeForMessage(roleguideRelPath)} resolves outside the project root ` +
|
|
645
|
+
`(${sanitizeForMessage(rgResolved.real)})`,
|
|
401
646
|
});
|
|
402
647
|
}
|
|
403
648
|
const marker = checkRoleguideMarkers(roleguideAbsPath, {
|
|
@@ -406,6 +651,353 @@ export function checkBehavioralInjection(projectRoot, teamSlug, teamsDir = 'mx-a
|
|
|
406
651
|
});
|
|
407
652
|
return { ...marker, teamSlug, displayName, roleguideRelPath };
|
|
408
653
|
}
|
|
654
|
+
export const REQUIRED_BEHAVIORAL_ELEMENTS = [
|
|
655
|
+
{
|
|
656
|
+
id: 'prior-art-gate',
|
|
657
|
+
label: 'prior-art gate',
|
|
658
|
+
patterns: [/prior[\s-]*art/i, /search (?:memories|memnexus) before/i],
|
|
659
|
+
},
|
|
660
|
+
{
|
|
661
|
+
id: 'decision-authority',
|
|
662
|
+
label: 'decision authority',
|
|
663
|
+
// The last two patterns exist because the first draft of this list reported
|
|
664
|
+
// eval's block — which HAS an authority section, headed "Authority and
|
|
665
|
+
// Accountability" and bounded by "a decision outside that authority" — as
|
|
666
|
+
// missing one. A checker that cries wolf on a compliant roleguide teaches
|
|
667
|
+
// teams to ignore it, which is the failure mode this whole issue is about.
|
|
668
|
+
patterns: [
|
|
669
|
+
/decision authority/i,
|
|
670
|
+
/\bfull authority\b/i,
|
|
671
|
+
/authority (?:and accountability|to (?:decide|ship|act|proceed))/i,
|
|
672
|
+
/(?:outside|beyond|exceeds?|within) (?:that |your |its |the )?authority\b/i,
|
|
673
|
+
],
|
|
674
|
+
},
|
|
675
|
+
{
|
|
676
|
+
id: 'anti-approval-seeking',
|
|
677
|
+
label: 'anti-approval-seeking',
|
|
678
|
+
patterns: [
|
|
679
|
+
/approval[\s-]*seeking/i,
|
|
680
|
+
/(?:do not|don'?t|never) (?:ask|wait) for (?:approval|permission|sign[\s-]*off)/i,
|
|
681
|
+
/without (?:repeatedly )?(?:requesting|seeking|asking for|waiting for) (?:approval|permission|sign[\s-]*off)/i,
|
|
682
|
+
/decide and execute/i,
|
|
683
|
+
],
|
|
684
|
+
},
|
|
685
|
+
{
|
|
686
|
+
id: 'delegation-stop-conditions',
|
|
687
|
+
label: 'delegation / stop conditions',
|
|
688
|
+
patterns: [/delegat/i, /stop condition/i, /\bescalate (?:to|when)\b/i],
|
|
689
|
+
},
|
|
690
|
+
];
|
|
691
|
+
/**
|
|
692
|
+
* Negators that flip a mention into its opposite, and the window they act over.
|
|
693
|
+
*
|
|
694
|
+
* DELIBERATELY NARROW. The window is 24 characters on the SAME LINE ending at
|
|
695
|
+
* the match, and the negator list is closed. That is tight enough that it cannot
|
|
696
|
+
* fire on ordinary prose ("Missing prior art sections are a Bar Raiser block"
|
|
697
|
+
* has no negator; "escalate when a decision exceeds your authority" has none
|
|
698
|
+
* either), while still catching the adversarial form Codex demonstrated: "no
|
|
699
|
+
* prior-art gate", "do not delegate or escalate".
|
|
700
|
+
*
|
|
701
|
+
* THE WINDOW STOPS AT `;` AND `—`, NOT ONLY AT `.` AND NEWLINE (security
|
|
702
|
+
* re-review, SF-D). Treating a semicolon as continuous prose made this rule
|
|
703
|
+
* report a COMPLIANT sentence as missing:
|
|
704
|
+
*
|
|
705
|
+
* Do not ask the PO; decide and execute.
|
|
706
|
+
*
|
|
707
|
+
* The only matching pattern is `/decide and execute/i`; the prefix ends
|
|
708
|
+
* `Do not ask the PO; ` — a negator 13 characters back with no full stop
|
|
709
|
+
* between — so the sole mention was judged negated and anti-approval-seeking was
|
|
710
|
+
* reported absent from a roleguide that states it plainly. That is the exact
|
|
711
|
+
* false positive this rule's design comment says it exists to avoid, and the
|
|
712
|
+
* register our own roleguides are written in. A semicolon or an em dash ends the
|
|
713
|
+
* clause a negator can govern, so the window ends there too.
|
|
714
|
+
*
|
|
715
|
+
* Note what this fix does NOT claim: the boundary is still syntactic. A negator
|
|
716
|
+
* in the same clause as the phrase it does not actually govern would still
|
|
717
|
+
* count. The 16-roleguide comparison is what bounds that risk empirically.
|
|
718
|
+
*/
|
|
719
|
+
const NEGATOR = /\b(?:no|not|never|without|don'?t|do not|does not|disabled?|disable|ignore[sd]?|ignoring|skip(?:s|ped)?)\b[^.;—\n]{0,24}$/i;
|
|
720
|
+
/**
|
|
721
|
+
* How much text before a match the negation window can possibly need.
|
|
722
|
+
*
|
|
723
|
+
* NEGATOR is `$`-anchored with a 24-character tail and a longest alternative of
|
|
724
|
+
* ~8 characters, so 64 is comfortably more than it can ever consume. Slicing the
|
|
725
|
+
* WHOLE prefix instead — `content.slice(0, m.index)` — allocated and scanned up
|
|
726
|
+
* to a full block per match: with the 128 KiB cap and a short pattern like
|
|
727
|
+
* `/delegat/i`, thousands of 64 KB allocations and ~10^8 character operations
|
|
728
|
+
* on the session-start path, to answer a question about the last 30 characters.
|
|
729
|
+
*/
|
|
730
|
+
const NEGATION_WINDOW = 64;
|
|
731
|
+
/**
|
|
732
|
+
* True when EVERY mention of this element is negated.
|
|
733
|
+
*
|
|
734
|
+
* ANY-NON-NEGATED-MATCH WINS, and that asymmetry is the point. Real roleguides
|
|
735
|
+
* negate these phrases all the time in legitimate instructions — eval's block
|
|
736
|
+
* says "Do not delegate broad exploration" a few lines below its "Minimum Team
|
|
737
|
+
* and Delegation" heading, and customer-portal's says "**No prior art found** —
|
|
738
|
+
* State explicitly…" inside a section that is entirely about the prior-art gate.
|
|
739
|
+
* Treating one negated mention as absence would fire on both, which is precisely
|
|
740
|
+
* the false positive this session already paid for once. Only a block where
|
|
741
|
+
* every single mention is negated is treated as not carrying the element.
|
|
742
|
+
*/
|
|
743
|
+
function allMentionsNegated(content, patterns) {
|
|
744
|
+
let sawMatch = false;
|
|
745
|
+
for (const pattern of patterns) {
|
|
746
|
+
// Fresh, global copy: the specs' patterns are shared and must not carry
|
|
747
|
+
// lastIndex state between calls.
|
|
748
|
+
const g = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`);
|
|
749
|
+
let m;
|
|
750
|
+
while ((m = g.exec(content)) !== null) {
|
|
751
|
+
sawMatch = true;
|
|
752
|
+
const window = content.slice(Math.max(0, m.index - NEGATION_WINDOW), m.index);
|
|
753
|
+
if (!NEGATOR.test(window))
|
|
754
|
+
return false; // a clean mention
|
|
755
|
+
if (m.index === g.lastIndex)
|
|
756
|
+
g.lastIndex++; // zero-width guard
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
return sawMatch;
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Which required elements are absent from `content`. Pure; never throws.
|
|
763
|
+
*
|
|
764
|
+
* "Absent" means: no pattern matched at all, OR every match was immediately
|
|
765
|
+
* preceded by a negator. See the section comment above for what this does and
|
|
766
|
+
* does not establish — it is a keyword heuristic, not a verification.
|
|
767
|
+
*/
|
|
768
|
+
export function findMissingBehavioralElements(content) {
|
|
769
|
+
return REQUIRED_BEHAVIORAL_ELEMENTS
|
|
770
|
+
.filter((el) => !el.patterns.some((p) => p.test(content)) || allMentionsNegated(content, el.patterns))
|
|
771
|
+
.map((el) => el.label);
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Assert that a behavioral block is non-empty AND carries all four required
|
|
775
|
+
* elements. Never throws.
|
|
776
|
+
*/
|
|
777
|
+
export function checkBehavioralCompleteness(content, rawLabel) {
|
|
778
|
+
const label = sanitizeForMessage(rawLabel);
|
|
779
|
+
const text = (content ?? '').trim();
|
|
780
|
+
if (!text) {
|
|
781
|
+
return {
|
|
782
|
+
ok: false,
|
|
783
|
+
missing: REQUIRED_BEHAVIORAL_ELEMENTS.map((el) => el.label),
|
|
784
|
+
problem: 'content-empty',
|
|
785
|
+
detail: `${label} has NO behavioral block content`,
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
const missing = findMissingBehavioralElements(text);
|
|
789
|
+
if (missing.length > 0) {
|
|
790
|
+
return {
|
|
791
|
+
ok: false, missing, problem: 'content-incomplete',
|
|
792
|
+
detail: `${label} has a behavioral block (${text.split('\n').length} lines) but it is ` +
|
|
793
|
+
`missing ${missing.length} of ${REQUIRED_BEHAVIORAL_ELEMENTS.length} required ` +
|
|
794
|
+
`element(s): ${missing.join(', ')}`,
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
return { ok: true, missing: [], problem: null, detail: null };
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Repo-relative path we are willing to hand to `git show <ref>:<path>`.
|
|
801
|
+
*
|
|
802
|
+
* `git show` interprets some leading forms specially (`:/`, `./`, `../` are
|
|
803
|
+
* resolved against the CURRENT DIRECTORY, not the tree root), so the safe set is
|
|
804
|
+
* stated positively: ordinary path characters, no segment equal to `.` or `..`,
|
|
805
|
+
* no leading slash, no leading dash (which git would read as an option).
|
|
806
|
+
*/
|
|
807
|
+
function isSafeRepoRelPath(p) {
|
|
808
|
+
if (!p || p.length > 512)
|
|
809
|
+
return false;
|
|
810
|
+
if (!/^[A-Za-z0-9._\-/]+$/.test(p))
|
|
811
|
+
return false;
|
|
812
|
+
if (p.startsWith('/') || p.startsWith('-'))
|
|
813
|
+
return false;
|
|
814
|
+
return p.split('/').every((seg) => seg !== '' && seg !== '.' && seg !== '..');
|
|
815
|
+
}
|
|
816
|
+
function runGit(repoPath, args) {
|
|
817
|
+
try {
|
|
818
|
+
const r = spawnSync('git', args, {
|
|
819
|
+
cwd: repoPath, encoding: 'utf-8', stdio: 'pipe',
|
|
820
|
+
// A hung git must not hang session start. 10s is far beyond a local object
|
|
821
|
+
// read; `fetch` is NOT run here (syncClaudeConfig already fetched).
|
|
822
|
+
timeout: 10_000,
|
|
823
|
+
maxBuffer: MAX_ROLEGUIDE_BYTES,
|
|
824
|
+
});
|
|
825
|
+
const errCode = r.error?.code;
|
|
826
|
+
return {
|
|
827
|
+
status: typeof r.status === 'number' ? r.status : 1,
|
|
828
|
+
stdout: r.stdout ?? '',
|
|
829
|
+
stderr: r.stderr ?? '',
|
|
830
|
+
overrun: errCode === 'ENOBUFS',
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
catch {
|
|
834
|
+
return { status: 1, stdout: '', stderr: 'git could not be executed', overrun: false };
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Read ONE regular-file blob out of `ref`.
|
|
839
|
+
*
|
|
840
|
+
* SYMLINKS ARE REJECTED BY MODE, not by realpath. A git tree entry carries the
|
|
841
|
+
* mode: a symbolic link is `120000` with the link target as its blob content, a
|
|
842
|
+
* submodule is `160000`, a directory is `040000`. Only `100644` / `100755` are
|
|
843
|
+
* read. This is the same ban the local path enforces (PO directive 2026-07-20)
|
|
844
|
+
* with a stronger guarantee: a blob's bytes are fixed by its object id, so there
|
|
845
|
+
* is no window between the mode check and the read, and nothing in a git tree
|
|
846
|
+
* can name a file outside the repository at all.
|
|
847
|
+
*/
|
|
848
|
+
function readTreeEntry(repoPath, ref, rawRelPath) {
|
|
849
|
+
// The path comes from a backticked token in the team catalog: untrusted input
|
|
850
|
+
// that this function is about to refuse. Refusing it is not a licence to echo
|
|
851
|
+
// it raw into the operator's terminal.
|
|
852
|
+
const relPath = rawRelPath;
|
|
853
|
+
const shown = sanitizeForMessage(rawRelPath);
|
|
854
|
+
const shownRef = sanitizeForMessage(ref);
|
|
855
|
+
if (!isSafeRepoRelPath(relPath)) {
|
|
856
|
+
return {
|
|
857
|
+
kind: 'rejected', problem: 'roleguide-path-escapes-root',
|
|
858
|
+
detail: `refusing to read "${shown}" from ${shownRef}: not a plain repo-relative path`,
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
const ls = runGit(repoPath, ['ls-tree', '--full-tree', '-z', ref, '--', relPath]);
|
|
862
|
+
if (ls.overrun) {
|
|
863
|
+
return {
|
|
864
|
+
kind: 'rejected', problem: 'content-too-large',
|
|
865
|
+
detail: `listing ${shown} in ${shownRef} produced more than ${MAX_ROLEGUIDE_BYTES / 1024} KiB`,
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
if (ls.status !== 0) {
|
|
869
|
+
return {
|
|
870
|
+
kind: 'unavailable',
|
|
871
|
+
reason: `git ls-tree ${shownRef} failed (${sanitizeForMessage(ls.stderr.trim()) || 'no output'})`,
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
const entry = ls.stdout.split('\0').find((l) => l.length > 0);
|
|
875
|
+
if (!entry) {
|
|
876
|
+
return { kind: 'unavailable', reason: `${shown} does not exist in ${shownRef}` };
|
|
877
|
+
}
|
|
878
|
+
const mode = entry.slice(0, entry.indexOf(' '));
|
|
879
|
+
const type = entry.split(' ')[1];
|
|
880
|
+
if (mode === '120000') {
|
|
881
|
+
return {
|
|
882
|
+
kind: 'rejected',
|
|
883
|
+
problem: relPath.includes('/teams/') ? 'team-file-symlink' : 'roleguide-symlink',
|
|
884
|
+
detail: `${shown} is a symbolic link in ${shownRef} — agent config must be regular files ` +
|
|
885
|
+
`(symlinked content never appears in a diff and is invisible to review)`,
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
if (type !== 'blob' || (mode !== '100644' && mode !== '100755')) {
|
|
889
|
+
return {
|
|
890
|
+
kind: 'rejected', problem: 'roleguide-not-regular-file',
|
|
891
|
+
detail: `${shown} in ${shownRef} is mode ${sanitizeForMessage(mode, 12)} (${sanitizeForMessage(type ?? "", 12)}), not a regular file`,
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
const show = runGit(repoPath, ['show', `${ref}:${relPath}`]);
|
|
895
|
+
if (show.overrun) {
|
|
896
|
+
// REJECTED, never `unavailable`: see GitRun.overrun. A file this size is a
|
|
897
|
+
// defect in the file, and answering "git could not serve it" would hand the
|
|
898
|
+
// session to the stale local tree.
|
|
899
|
+
return {
|
|
900
|
+
kind: 'rejected', problem: 'content-too-large',
|
|
901
|
+
detail: `${shown} in ${shownRef} is over the ${MAX_ROLEGUIDE_BYTES / 1024} KiB roleguide ` +
|
|
902
|
+
`limit — refusing to read it, and NOT falling back to the local working tree`,
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
if (show.status !== 0) {
|
|
906
|
+
return {
|
|
907
|
+
kind: 'unavailable',
|
|
908
|
+
reason: `git show ${shownRef}:${shown} failed (${sanitizeForMessage(show.stderr.trim()) || 'no output'})`,
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
return { kind: 'ok', text: show.stdout };
|
|
912
|
+
}
|
|
913
|
+
/** Slug that is safe both as a filename and inside a `git show` pathspec. */
|
|
914
|
+
function isSafeTeamSlug(slug) {
|
|
915
|
+
return /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) && slug.length <= 128 && !slug.includes('..');
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* Resolve a team's behavioral block from `<remote>/<baseBranch>`, falling back to
|
|
919
|
+
* the local working tree ONLY when git cannot serve the bytes. Never throws.
|
|
920
|
+
*
|
|
921
|
+
* WHY GIT FIRST (#4707). The previous read came from `projectRoot`, a working
|
|
922
|
+
* tree nobody updates; it was 82 commits stale and had never seen the markers
|
|
923
|
+
* eval's roleguide gained four days earlier. `syncClaudeConfig` had already
|
|
924
|
+
* settled this question for `.claude/` — read the ref, not the checkout — and the
|
|
925
|
+
* behavioral block is a higher-value sink than the config it sits next to.
|
|
926
|
+
*
|
|
927
|
+
* WHEN THE FALLBACK IS RIGHT. A team catalog entry or roleguide that has not
|
|
928
|
+
* merged yet is genuinely absent from the ref, and refusing to start on that
|
|
929
|
+
* basis would make a brand-new team unstartable. So the fallback stays — but the
|
|
930
|
+
* caller MUST surface it, because "read a stale checkout" is exactly the silent
|
|
931
|
+
* behavior this change exists to remove.
|
|
932
|
+
*/
|
|
933
|
+
export function resolveBehavioralInjection(projectRoot, teamSlug, opts) {
|
|
934
|
+
const remote = opts.remote ?? 'origin';
|
|
935
|
+
const teamsDir = opts.teamsDir ?? 'mx-agent-system/teams';
|
|
936
|
+
const ref = `${remote}/${opts.baseBranch}`;
|
|
937
|
+
const shownSlug = sanitizeForMessage(teamSlug, 80);
|
|
938
|
+
const shownRef = sanitizeForMessage(ref);
|
|
939
|
+
const fallback = (reason) => ({
|
|
940
|
+
result: checkBehavioralInjection(projectRoot, teamSlug, teamsDir),
|
|
941
|
+
source: 'local', ref, fallbackReason: reason,
|
|
942
|
+
});
|
|
943
|
+
const fromGit = (extra) => ({
|
|
944
|
+
result: {
|
|
945
|
+
ok: false, content: null, raw: null, problem: null, detail: null,
|
|
946
|
+
teamSlug, displayName: teamSlug, roleguideRelPath: null, ...extra,
|
|
947
|
+
},
|
|
948
|
+
source: 'git', ref, fallbackReason: null,
|
|
949
|
+
});
|
|
950
|
+
if (!isSafeTeamSlug(teamSlug)) {
|
|
951
|
+
// NOT a fallback: an unsafe slug must not be retried against the filesystem.
|
|
952
|
+
return fromGit({
|
|
953
|
+
problem: 'invalid-team-slug',
|
|
954
|
+
detail: `invalid team slug "${shownSlug}"`,
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
// The ref itself must exist before anything else is attributed to it — a
|
|
958
|
+
// detached/offline clone with no remote-tracking branch is an availability
|
|
959
|
+
// problem, not a roleguide problem.
|
|
960
|
+
const refCheck = runGit(opts.repoPath, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
|
|
961
|
+
if (refCheck.status !== 0) {
|
|
962
|
+
return fallback(`${shownRef} is not available in ${sanitizeForMessage(opts.repoPath)}`);
|
|
963
|
+
}
|
|
964
|
+
const teamRel = `${teamsDir}/${teamSlug}.md`;
|
|
965
|
+
const teamRead = readTreeEntry(opts.repoPath, ref, teamRel);
|
|
966
|
+
if (teamRead.kind === 'unavailable')
|
|
967
|
+
return fallback(teamRead.reason);
|
|
968
|
+
if (teamRead.kind === 'rejected') {
|
|
969
|
+
return fromGit({ problem: teamRead.problem, detail: teamRead.detail });
|
|
970
|
+
}
|
|
971
|
+
const teamFileContent = teamRead.text;
|
|
972
|
+
const displayNameLine = teamFileContent.split('\n').find((l) => l.startsWith('Display name:'));
|
|
973
|
+
const displayName = safeDisplayName(displayNameLine ? displayNameLine.replace('Display name:', '').trim() : '', teamSlug);
|
|
974
|
+
const roleguideLineRaw = teamFileContent.split('\n').find((l) => l.startsWith('Roleguide:'));
|
|
975
|
+
if (!roleguideLineRaw) {
|
|
976
|
+
return fromGit({
|
|
977
|
+
displayName, problem: 'roleguide-line-missing',
|
|
978
|
+
detail: `no 'Roleguide:' line in ${sanitizeForMessage(teamRel)} on ${shownRef}`,
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
const roleguideMatch = roleguideLineRaw.match(/`([^`]+)`/);
|
|
982
|
+
if (!roleguideMatch) {
|
|
983
|
+
return fromGit({
|
|
984
|
+
displayName, problem: 'roleguide-path-unparseable',
|
|
985
|
+
detail: `could not parse a backticked roleguide path from ${sanitizeForMessage(teamRel)} on ${shownRef}`,
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
const roleguideRelPath = roleguideMatch[1];
|
|
989
|
+
const rgRead = readTreeEntry(opts.repoPath, ref, roleguideRelPath);
|
|
990
|
+
if (rgRead.kind === 'unavailable')
|
|
991
|
+
return fallback(rgRead.reason);
|
|
992
|
+
if (rgRead.kind === 'rejected') {
|
|
993
|
+
return fromGit({ displayName, roleguideRelPath, problem: rgRead.problem, detail: rgRead.detail });
|
|
994
|
+
}
|
|
995
|
+
const marker = extractMarkerBlock(rgRead.text, `${roleguideRelPath} (${ref})`); // sanitized inside
|
|
996
|
+
return {
|
|
997
|
+
result: { ...marker, teamSlug, displayName, roleguideRelPath },
|
|
998
|
+
source: 'git', ref, fallbackReason: null,
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
409
1001
|
/**
|
|
410
1002
|
* One-line, actionable remediation text for a failed check. Shape mirrors
|
|
411
1003
|
* `describeHookProblems` in claude.ts: state what is wrong, then the exact fix.
|
|
@@ -415,6 +1007,30 @@ export function describeBehavioralProblem(r) {
|
|
|
415
1007
|
return '';
|
|
416
1008
|
const what = r.detail ?? 'behavioral block unavailable';
|
|
417
1009
|
switch (r.problem) {
|
|
1010
|
+
case 'content-incomplete': {
|
|
1011
|
+
// Name WHICH elements are absent (#4707). "Incomplete" alone sends the
|
|
1012
|
+
// operator to re-read a 60-line block looking for something that is not
|
|
1013
|
+
// there; the list says what to write.
|
|
1014
|
+
const missing = 'missing' in r && r.missing.length > 0
|
|
1015
|
+
? r.missing.join(', ')
|
|
1016
|
+
: REQUIRED_BEHAVIORAL_ELEMENTS.map((e) => e.label).join(', ');
|
|
1017
|
+
return `${what}. Fix: add the missing element(s) — ${missing} — inside the roleguide's ` +
|
|
1018
|
+
`${BEHAVIORAL_START_MARKER} / ${BEHAVIORAL_END_MARKER} block. A block that carries none ` +
|
|
1019
|
+
`of them reinforces nothing on the turns it is injected into.`;
|
|
1020
|
+
}
|
|
1021
|
+
case 'content-too-large':
|
|
1022
|
+
return `${what}. Fix: cut the roleguide's behavioral block down to the sections that must ` +
|
|
1023
|
+
`re-inject on every turn, and move reference material outside the markers. Note the ` +
|
|
1024
|
+
`read was REFUSED — it did not silently fall back to a local copy.`;
|
|
1025
|
+
case 'content-control-characters':
|
|
1026
|
+
return `${what}. Fix: remove the control character from the roleguide. Markdown needs ` +
|
|
1027
|
+
`none, and an escape sequence here can repaint the operator's terminal — including this ` +
|
|
1028
|
+
`warning.`;
|
|
1029
|
+
case 'markers-repeated':
|
|
1030
|
+
return `${what}. Fix: keep exactly ONE ${BEHAVIORAL_START_MARKER} line and ONE ` +
|
|
1031
|
+
`${BEHAVIORAL_END_MARKER} line in the roleguide, and merge the sections that belong in ` +
|
|
1032
|
+
`the block between them. (Mentions of the markers inside a sentence, a table cell or ` +
|
|
1033
|
+
`backticks are not counted — only a line that is exactly the marker.)`;
|
|
418
1034
|
case 'markers-missing':
|
|
419
1035
|
case 'markers-inverted':
|
|
420
1036
|
case 'content-empty':
|