Skip to content

Commit 04cd809

Browse files
authored
fix(records): write front matter keys and values literally (#1138) thanks @dwin-gharibi
Store front-matter keys and values literally so dollar-pattern label names cannot corrupt persisted review records. Includes focused regression coverage and current-head Crabbox proof. Co-authored-by: Dwin Gharibi <[email protected]>
1 parent bd86954 commit 04cd809

6 files changed

Lines changed: 498 additions & 5 deletions

File tree

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# Proof: label names are written to a record verbatim
2+
3+
## Claim
4+
5+
A GitHub label whose name contains `$&`, `` $` ``, `$'` or `$$` is stored in a
6+
record's `labels:` front matter exactly as given, the record around it is left
7+
intact, and front matter keys are matched literally instead of being compiled as
8+
regular expressions.
9+
10+
## Exercised surface
11+
12+
`createRecordMetadata(...).replaceFrontMatterValue` and the matching readers
13+
(`.frontMatterField`, `.frontMatterValue`, `.frontMatterStringArray`) in
14+
`dist/clawsweeper-record-metadata.js`.
15+
16+
`src/clawsweeper-apply-report-labels.ts` writes the synced label set with
17+
18+
```ts
19+
markdown = replaceFrontMatterValue(markdown, "labels", JSON.stringify(item.labels));
20+
```
21+
22+
`item.labels` is the label set returned by the label sync for the reviewed item, so
23+
the names come from the reviewed repository. `String.prototype.replace` treats `$&`,
24+
`` $` ``, `$'` and `$$` in its *replacement* argument as expansion patterns, so those
25+
names were being expanded against the match instead of inserted.
26+
27+
## Scenario / fixture
28+
29+
`run-proof.mjs` starts from a record holding `repository`, `number`, `labels`,
30+
`title` and a body, then writes label sets through the shipped writer and reads them
31+
back through the shipped readers:
32+
33+
1. **Verbatim storage** — ordinary names plus every replacement pattern, including a
34+
mixed set (`["needs-triage", "$&"]`) that mirrors a real sync result.
35+
2. **Valid JSON** — the stored text must still `JSON.parse` back to what was written,
36+
because `frontMatterStringArray` silently falls back to comma-splitting when it
37+
does not.
38+
3. **Record integrity** — `title`, `number`, the body, and the `---` delimiters must
39+
be unchanged after the write.
40+
4. **Literal keys** — keys containing `.`, `+`, `(`, `[`, `|` and `*` must read and
41+
update in place, and `a.c` must not match a line reading `aXc:`.
42+
43+
## Command and environment
44+
45+
```
46+
bash docs/proof/record-front-matter-literal-write/stage-before.sh
47+
crabbox run --provider local-container --local-container-image node:24 --no-hydrate \
48+
--artifact-glob '.artifacts/**' -- \
49+
bash docs/proof/record-front-matter-literal-write/run-proof.sh
50+
```
51+
52+
Proof contract — what a passing run must show. The **observed run for the current
53+
head (lease, run id, artifact, redacted output) lives in the PR body**, which is
54+
where AGENTS.md requires current proof to sit. No lease id is pinned here on
55+
purpose: editing this file changes the head, which would immediately make a pinned
56+
run describe a different commit than the one under review.
57+
58+
| | |
59+
|---|---|
60+
| provider | Crabbox `local-container` (runtime `docker`) |
61+
| image | `node:24`; the script refuses to run below Node 24 |
62+
| result | **PROOF PASSED** (all fixtures); focused suite `4/4`; exit `0` |
63+
| head | echoed from `PROOF_HEAD`, forwarded with `--allow-env` |
64+
| tracked state | unchanged at every checkpoint; identical `package.json` and `pnpm-lock.yaml` digests at sync and at end of run |
65+
66+
`stage-before.sh` exists because container images carry no `.git`: it writes the
67+
base version of the changed file into `before/` on the host, where rsync picks it up
68+
as a dirty file. When git *is* available `run-proof.sh` re-derives that file, so the
69+
staged copy cannot drift from the base commit.
70+
71+
The script refuses to run below Node 24, installs the pinned pnpm into a
72+
user-writable prefix, builds the Node lane, and runs the fixtures twice: once
73+
against the module compiled from the base commit and once against this branch.
74+
75+
## Observed result
76+
77+
Against the pre-fix module 17 assertions fail. Beyond the label sets themselves,
78+
a label named `$'` also fails `title survives` and `delimiters are unchanged` — the
79+
expansion pulls the text following the match into the field, so the write damages the
80+
record body, not just the one value. Keys containing `(`, `[`, `|`, `+` or `*` either
81+
throw `SyntaxError: Invalid regular expression` or match the wrong line, and `a.c`
82+
matches `aXc`. Against this branch every assertion passes. The ordinary `["bug"]`
83+
case passes in both runs, which is what shows the change is confined to names that
84+
carry a replacement pattern; the script fails the proof if that case ever regresses.
85+
86+
## Artifact / trace
87+
88+
`.crabbox/runs/run_26f52fe84002/run_26f52fe84002-artifacts.tgz` holds
89+
`.artifacts/record-front-matter-literal-write-proof/` with `before-output.txt`,
90+
`proof-output.txt`, `focused-tests.txt`, and the install/build logs.
91+
92+
## The run cannot alter the head it is proving
93+
94+
The script records `package.json` and `pnpm-lock.yaml` digests plus
95+
`git status --porcelain` at sync, then re-checks them after dependency installation
96+
and at the end of the run; any drift aborts with a diff. The platform-native
97+
TypeScript fallback installs into a disposable prefix outside the workspace rather
98+
than writing tracked dependency metadata, so the recorded result does not disturb
99+
the head it is describing.
100+
101+
## Limits
102+
103+
This proves the record reader and writer in
104+
`src/clawsweeper-record-metadata.ts`. The same raw-interpolation shape exists in
105+
`src/repair/workflow-utils.ts`, `src/repair/create-job.ts`,
106+
`src/repair/target-fanout.ts`, `src/repair/comment-router-core.ts`,
107+
`src/commit-sweeper.ts`, `src/decision-packets.ts` and two scripts; those are left
108+
for a separate change and are tracked in the linked issue. No shipped caller passes a
109+
key containing regex syntax today, so part 4 hardens the advertised `key: string`
110+
contract rather than fixing an observed failure — part 1 through part 3 are the
111+
reachable defect. The proof does not call GitHub; it starts from the label set the
112+
sync returns.
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
// Real-behavior proof: a GitHub label name containing a `$`-replacement pattern must
2+
// be stored in a record's front matter verbatim, and a front matter key must be
3+
// matched literally rather than compiled as a regular expression.
4+
//
5+
// Exercises the shipped factory in dist/clawsweeper-record-metadata.js — the module
6+
// the label apply lane writes `labels:` through.
7+
import { resolve } from "node:path";
8+
import { pathToFileURL } from "node:url";
9+
10+
// `--module <path>` swaps in a differently compiled build of the same module so the
11+
// runner can be pointed at the pre-fix source for a before/after contrast.
12+
const moduleFlag = process.argv.indexOf("--module");
13+
const modulePath =
14+
moduleFlag === -1
15+
? new URL("../../../dist/clawsweeper-record-metadata.js", import.meta.url).href
16+
: pathToFileURL(resolve(process.argv[moduleFlag + 1] ?? "")).href;
17+
const { createRecordMetadata } = await import(modulePath);
18+
console.log(`module under test: ${modulePath.replace(/^file:\/\//, "")}\n`);
19+
20+
const noop = () => null;
21+
const metadata = createRecordMetadata({
22+
reportFileName: (repo, number) => `${number}.md`,
23+
markdownRepository: () => "openclaw/openclaw",
24+
isVerifiedFixedCloseReason: () => false,
25+
isOlderThanDays: () => false,
26+
timestampMs: (value) => (value ? Date.parse(value) : null),
27+
pullHeadShaFromReport: noop,
28+
reviewLeaseRevisionFromReport: noop,
29+
lockedConversationApplyReason: noop,
30+
markdownFiles: () => [],
31+
numberForMarkdownFile: () => 0,
32+
});
33+
34+
let failures = 0;
35+
const check = (ok, label, detail) => {
36+
console.log(` ${ok ? "PASS" : "FAIL"} ${label}`);
37+
if (!ok) {
38+
failures += 1;
39+
if (detail) console.log(` ${detail}`);
40+
}
41+
};
42+
43+
const RECORD = [
44+
"---",
45+
"repository: openclaw/openclaw",
46+
"number: 42",
47+
"labels: []",
48+
"title: Fix the thing",
49+
"---",
50+
"",
51+
"Codex review: ready.",
52+
"",
53+
].join("\n");
54+
55+
console.log("== 1. label names are stored verbatim ==");
56+
// The apply lane writes labels as replaceFrontMatterValue(markdown, "labels",
57+
// JSON.stringify(item.labels)). Those names come from the reviewed repository and
58+
// GitHub permits `$`, a backtick and a quote inside a label name.
59+
for (const labels of [
60+
["bug"],
61+
["$&"],
62+
["$`"],
63+
["$'"],
64+
["a$&b"],
65+
["$$"],
66+
["P$1"],
67+
["needs-triage", "$&"],
68+
]) {
69+
const written = JSON.stringify(labels);
70+
const next = metadata.replaceFrontMatterValue(RECORD, "labels", written);
71+
const raw = metadata.frontMatterValue(next, "labels");
72+
const readBack = metadata.frontMatterStringArray(next, "labels");
73+
const ok = raw === written && JSON.stringify(readBack) === written;
74+
check(ok, `labels ${written}`, `stored ${JSON.stringify(raw)}, read back ${JSON.stringify(readBack)}`);
75+
}
76+
77+
console.log("\n== 2. the stored value stays valid JSON ==");
78+
for (const labels of [["$`"], ["$'"], ["$&"]]) {
79+
const written = JSON.stringify(labels);
80+
const next = metadata.replaceFrontMatterValue(RECORD, "labels", written);
81+
const raw = metadata.frontMatterValue(next, "labels") ?? "";
82+
let parsed = null;
83+
let error = null;
84+
try {
85+
parsed = JSON.parse(raw);
86+
} catch (cause) {
87+
error = String(cause);
88+
}
89+
check(
90+
error === null && JSON.stringify(parsed) === written,
91+
`JSON.parse round-trips ${written}`,
92+
error ?? `parsed ${JSON.stringify(parsed)}`,
93+
);
94+
}
95+
96+
console.log("\n== 3. the rest of the record is untouched ==");
97+
{
98+
const next = metadata.replaceFrontMatterValue(RECORD, "labels", JSON.stringify(["$'"]));
99+
check(metadata.frontMatterValue(next, "title") === "Fix the thing", "title survives");
100+
check(metadata.frontMatterValue(next, "number") === "42", "number survives");
101+
check(next.includes("Codex review: ready."), "body survives");
102+
check(next.split("---").length === RECORD.split("---").length, "delimiters are unchanged");
103+
}
104+
105+
console.log("\n== 4. keys are matched literally ==");
106+
for (const key of ["a.c", "a+b", "x(y", "k[0]", "q|r", "n*m"]) {
107+
const record = ["---", `${key}: original`, "---", "", "body", ""].join("\n");
108+
let readOk = false;
109+
let writeOk = false;
110+
let error = null;
111+
try {
112+
readOk = metadata.frontMatterValue(record, key) === "original";
113+
const next = metadata.replaceFrontMatterValue(record, key, "updated");
114+
writeOk = metadata.frontMatterValue(next, key) === "updated" && !next.includes(`${key}: original`);
115+
} catch (cause) {
116+
error = String(cause);
117+
}
118+
check(readOk && writeOk, `key ${JSON.stringify(key)} reads and updates in place`, error);
119+
}
120+
{
121+
// A literal key must not match a different, regex-equivalent line.
122+
const decoy = ["---", "aXc: decoy", "---", "", "body", ""].join("\n");
123+
check(metadata.frontMatterField(decoy, "a.c").status === "absent", "`a.c` does not match `aXc`");
124+
}
125+
126+
console.log(`\n${failures === 0 ? "PROOF PASSED" : `PROOF FAILED (${failures})`}`);
127+
process.exit(failures === 0 ? 0 : 1);

0 commit comments

Comments
 (0)