Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

fix: quote frontmatter as a YAML scalar, not by swapping quote characters (#181)

Brenno Ferrari7614d1dde216
diff --git a/.claude/scripts/lib/mcp-capture.ts b/.claude/scripts/lib/mcp-capture.ts
index 6bff00c..18d90f0 100644
--- a/.claude/scripts/lib/mcp-capture.ts
+++ b/.claude/scripts/lib/mcp-capture.ts
@@ -71,6 +71,36 @@ export function slugifyTitle(title: unknown): string {
.toLowerCase();
}
+/**
+ * A YAML **single**-quoted scalar, which is the only quoting a caller-supplied
+ * string can survive.
+ *
+ * The double-quoted form looks equivalent and is not, because it processes
+ * escapes. A title carrying a Windows path — `C:\temp\x`, which this repo's own
+ * fixtures deliberately contain — becomes `"C:\temp\x"`, where `\t` is a TAB
+ * and `\x` demands two hex digits. That is a parse error, and it takes the
+ * whole frontmatter block with it rather than just the one field. Swapping `"`
+ * for `'` inside a double-quoted scalar, which is what this file used to do,
+ * defends against exactly one of the characters that matter.
+ *
+ * In the single-quoted form the only escape is `''` for a literal quote, and a
+ * backslash is a backslash. Whitespace is flattened here rather than at the
+ * call sites, because a newline is the other way a scalar ends early: the
+ * continuation line lands at column zero, under-indented for the block it is
+ * inside, and the document is broken from there down.
+ *
+ * Flattening at the boundary is deliberate — every field this wraps is
+ * single-line by contract, so there is no case where a caller wants the raw
+ * newline preserved and a helper that guaranteed it only sometimes would be
+ * worth less than one that always does.
+ */
+export function yamlQuoted(text: unknown): string {
+ const flat = String(text ?? "")
+ .replace(/\s+/g, " ")
+ .trim();
+ return `'${flat.replace(/'/g, "''")}'`;
+}
+
/**
* A description that stops at a word, not mid-syllable.
*
@@ -92,7 +122,6 @@ export function slugifyTitle(title: unknown): string {
*/
export function clampDescription(text: unknown, max: number = DESCRIPTION_MAX): string {
const flat = String(text ?? "")
- .replace(/"/g, "'")
.replace(/\s+/g, " ")
.trim();
if (flat.length <= max) return flat;
@@ -283,12 +312,12 @@ export function renderCapture(
// round-trip through slugification, and `resolvableNames` has read aliases
// since it was written — for exactly this class of problem, where a note's
// real name and its file's name differ.
- const aliases = title ? ["aliases:", ` - "${title.replace(/"/g, "'")}"`] : [];
+ const aliases = title ? ["aliases:", ` - ${yamlQuoted(title)}`] : [];
return [
"---",
`date: ${day}`,
- `description: "${clampDescription(summary)}"`,
+ `description: ${yamlQuoted(clampDescription(summary))}`,
...aliases,
"tags:",
input.kind === "decision" ? " - decision" : " - project-note",
diff --git a/.claude/scripts/lib/mcp-memory-bridge.ts b/.claude/scripts/lib/mcp-memory-bridge.ts
index 2799084..5f0ed7d 100644
--- a/.claude/scripts/lib/mcp-memory-bridge.ts
+++ b/.claude/scripts/lib/mcp-memory-bridge.ts
@@ -48,6 +48,31 @@ export interface MemoryDigest extends Facets {
* in either the block or the inline form. Same rule the vault's own wikilink
* checker applies.
*/
+/**
+ * Undo a YAML scalar's quoting, rather than merely removing its quote marks.
+ *
+ * Stripping the outer quotes is not the same operation and differs on exactly
+ * the values that need it. In a single-quoted scalar `''` is one literal quote,
+ * so `'It''s here'` unquoted by character removal yields `It''s here` — a name
+ * no wikilink will ever match, and one an author looking at the rendered note
+ * would swear is present. In a double-quoted scalar the escapes are C-style,
+ * so `\\` is one backslash.
+ *
+ * This matters more since captures began carrying their title as an alias: an
+ * apostrophe is ordinary in a title and would otherwise silently cost the note
+ * its only resolvable name.
+ */
+export function unquoteScalar(raw: string): string {
+ const t = raw.trim();
+ if (t.length >= 2 && t.startsWith("'") && t.endsWith("'")) {
+ return t.slice(1, -1).replace(/''/g, "'");
+ }
+ if (t.length >= 2 && t.startsWith('"') && t.endsWith('"')) {
+ return t.slice(1, -1).replace(/\\(["\\])/g, "$1");
+ }
+ return t;
+}
+
export function resolvableNames(files: readonly VisibleFile[]): Set<string> {
const names = new Set<string>();
for (const f of files) {
@@ -58,13 +83,13 @@ export function resolvableNames(files: readonly VisibleFile[]): Set<string> {
if (block?.[1]) {
for (const line of block[1].split("\n")) {
const m = line.match(/^\s*-\s*(.+?)\s*$/);
- if (m?.[1]) names.add(m[1].replace(/^["']|["']$/g, "").toLowerCase());
+ if (m?.[1]) names.add(unquoteScalar(m[1]).toLowerCase());
}
}
const inline = head.match(/^aliases:\s*\[(.*)\]\s*$/m);
if (inline?.[1]) {
for (const part of inline[1].split(",")) {
- const name = part.trim().replace(/^["']|["']$/g, "").toLowerCase();
+ const name = unquoteScalar(part).toLowerCase();
if (name) names.add(name);
}
}
diff --git a/.claude/scripts/tests/mcp-capture.test.ts b/.claude/scripts/tests/mcp-capture.test.ts
index 7c6cf0d..b9362b4 100644
--- a/.claude/scripts/tests/mcp-capture.test.ts
+++ b/.claude/scripts/tests/mcp-capture.test.ts
@@ -25,6 +25,7 @@ import {
renderCapture,
captureNote,
clampDescription,
+ yamlQuoted,
type Destination,
} from "../lib/mcp-capture.ts";
import type { ExposurePolicy } from "../lib/mcp-exposure.ts";
@@ -181,7 +182,7 @@ describe("rendering a capture", () => {
const md = renderCapture(BASIC, dest, "atlas", new Set(["atlas"]), NOW);
assert.match(md, /^---\n/);
assert.match(md, /date: 2026-07-26/);
- assert.match(md, /description: "Shipped the archive command behind a flag\."/);
+ assert.match(md, /description: 'Shipped the archive command behind a flag\.'/);
assert.match(md, /project: atlas/);
assert.match(md, /source_repo: atlas/);
});
@@ -215,7 +216,11 @@ describe("rendering a capture", () => {
test("a quote in the summary cannot break the frontmatter", () => {
const md = renderCapture({ ...BASIC, summary: 'He said "hello" today' }, dest, "atlas", new Set(), NOW);
const front = md.slice(0, md.indexOf("\n---", 4));
- assert.ok(!/description: ".*".*"/.test(front.split("\n").find((l) => l.startsWith("description:")) ?? ""));
+ const line = front.split("\n").find((l) => l.startsWith("description:")) ?? "";
+ // A double quote is now ordinary content, because the scalar is
+ // single-quoted. What must not appear is an unescaped single quote.
+ assert.match(line, /^description: '.*'$/);
+ assert.equal(line, `description: 'He said "hello" today'`);
});
test("the routing decision is recorded in the note itself", () => {
@@ -323,13 +328,13 @@ describe("a capture is reachable by its own title", () => {
test("the title is carried as an alias, because the basename never is", () => {
const title = "I3 lands: a soak over the whole pipeline";
const md = renderCapture({ title, summary: "s", kind: "note" }, dest, "atlas", new Set(), NOW);
- assert.match(md, /^aliases:\n {2}- "I3 lands: a soak over the whole pipeline"$/m);
+ assert.match(md, /^aliases:\n {2}- 'I3 lands: a soak over the whole pipeline'$/m);
});
test("a title with a quote cannot break the frontmatter", () => {
const md = renderCapture({ title: 'The "obvious" fix', summary: "s", kind: "note" }, dest, "atlas", new Set(), NOW);
- assert.match(md, /^ {2}- "The 'obvious' fix"$/m);
- assert.doesNotMatch(md, /- "The "obvious/);
+ // A double quote is ordinary content inside a single-quoted scalar.
+ assert.match(md, /^ {2}- 'The "obvious" fix'$/m);
});
test("an empty title emits no alias block rather than an empty one", () => {
@@ -337,6 +342,70 @@ describe("a capture is reachable by its own title", () => {
assert.doesNotMatch(md, /^aliases:/m);
});
+ /**
+ * The two characters that end a scalar early, and neither is a quote.
+ *
+ * A double-quoted YAML scalar processes escapes, so a Windows path is a parse
+ * error (`\t` is TAB, `\x` wants two hex digits) — and this repo's own
+ * fixtures carry `C:\` paths on purpose. A newline ends the scalar at a
+ * column-zero continuation, which is under-indented for the block it sits in.
+ * Either one takes the WHOLE frontmatter block down, not just its own field,
+ * which is why these are asserted on the document rather than on the value.
+ */
+ const HOSTILE: ReadonlyArray<readonly [string, string]> = [
+ ["a newline", "First line\nSecond line"],
+ ["a Windows path", "A path C:\\temp\\x"],
+ ["a single quote", "It's the resolver's problem"],
+ ["a YAML comment marker", "I3: #5 lands - done"],
+ ];
+
+ for (const [label, title] of HOSTILE) {
+ test(`${label} in the title cannot break the frontmatter`, () => {
+ const md = renderCapture({ title, summary: title, kind: "note" }, dest, "atlas", new Set(), NOW);
+
+ assert.equal((md.match(/^---$/gm) ?? []).length, 2, "exactly one frontmatter block");
+
+ const front = md.slice(4, md.indexOf("\n---\n", 4));
+ // Scoped to the aliases block: `tags:` also emits ` - ` items, and a
+ // filter over the whole frontmatter counts those as extra alias lines.
+ const aliasBlock = front.match(/^aliases:\n((?: {2}- .*\n?)+)/m);
+ const aliasLines = (aliasBlock?.[1] ?? "").split("\n").filter(Boolean);
+ assert.equal(aliasLines.length, 1, `the alias must occupy one line, got ${JSON.stringify(aliasLines)}`);
+ assert.match(aliasLines[0]!, /^ {2}- '.*'$/, "single-quoted scalar");
+
+ // No line of the frontmatter may start a new key after the block began
+ // unexpectedly — a leaked newline shows up exactly here.
+ for (const line of front.split("\n")) {
+ assert.ok(line === "" || /^(\S+:|\s+-\s|\s+\S+:)/.test(line), `stray frontmatter line: ${JSON.stringify(line)}`);
+ }
+ });
+ }
+
+ test("a backslash survives literally rather than as an escape", () => {
+ const md = renderCapture({ title: "A path C:\\temp\\x", summary: "s", kind: "note" }, dest, "atlas", new Set(), NOW);
+ assert.match(md, /^ {2}- 'A path C:\\temp\\x'$/m);
+ });
+
+ test("a single quote is doubled, which is the only escape the form has", () => {
+ assert.equal(yamlQuoted("It's here"), "'It''s here'");
+ assert.equal(yamlQuoted('He said "hi"'), `'He said "hi"'`);
+ assert.equal(yamlQuoted("a\n\nb"), "'a b'");
+ });
+
+ test("round trip: a hostile title still resolves through resolvableNames", () => {
+ for (const [, title] of HOSTILE) {
+ withVault((dir) => {
+ captureNote(dir, POLICY, {}, null, { title, summary: "s", kind: "note" }, new Set(), { now: NOW });
+ const files = readdirSync(join(dir, "inbox"));
+ const label = files[0]!.replace(/\.md$/, "");
+ const resolvable = resolvableNames([{ label, full: join(dir, "inbox", files[0]!), scope: "inbox" }]);
+ // Whitespace is flattened by the scalar, so that is the name to expect.
+ const flat = title.replace(/\s+/g, " ").trim().toLowerCase();
+ assert.ok(resolvable.has(flat), `must resolve by ${JSON.stringify(flat)}`);
+ });
+ }
+ });
+
/**
* The regression that motivated #180, asserted end to end rather than on the
* alias line alone. Writing the alias is the mechanism; being resolvable is
@@ -413,7 +482,7 @@ describe("clamping a description", () => {
assert.doesNotMatch(clampDescription("one two three, four five six seven", 22), /[,;:–—-]…$/);
});
- test("whitespace is flattened and quotes made frontmatter-safe", () => {
- assert.equal(clampDescription('a\n\nb "c"', 150), "a b 'c'");
+ test("whitespace is flattened, and quoting is left to the scalar", () => {
+ assert.equal(clampDescription('a\n\nb "c"', 150), 'a b "c"');
});
});