Skip to content

fix(frontmatter): preserve malformed skill metadata - #383

Merged
jeff-r2026 merged 2 commits into
mainfrom
codex/fix-frontmatter-object-validation
Sep 1, 2026
Merged

jeff-r2026 merged 2 commits into
mainfrom
codex/fix-frontmatter-object-validation

Conversation

@jeff-r2026

Copy link
Copy Markdown
Collaborator

Fixes the malformed frontmatter regression introduced by #378.

  • Validate that parsed frontmatter is a YAML mapping before accessing or serializing fields.
  • Leave malformed/scalar frontmatter unchanged instead of throwing or dropping metadata.
  • Add regression coverage for malformed mapping and scalar frontmatter.

Tests: npm test -- --run, npm run typecheck

@jeff-r2026

Copy link
Copy Markdown
Collaborator Author

The new guard is bypassed on the second parse

I ran this branch end-to-end with the real CLI (teamai pull --force, isolated sandbox: temp HOME, project scope, local bare-repo remote). The valid guard works for the first document with a given frontmatter block and is silently bypassed for every one after it — so the regression this PR targets is still reachable on the normal pull path.

Root cause

gray-matter writes the file object into its module-level matter.cache before parsing, keyed on the frontmatter block string, and serves cache hits via Object.assign({}, cached) — a shallow copy. Two consequences at src/utils/frontmatter.ts:44:

  1. When YAML parsing throws, the cached entry survives with data = {}. The next splitFrontmatter on the same block reads the cache, never throws, and returns valid: true.
  2. The returned data is the same object reference the cache holds. ensureSkillFrontmatter mutates it (data['name'] = skillName), writing straight back into the global cache.

Both matter because SkillsHandler.pullItem (src/resources/skills.ts:459) and deployBuiltinSkills (src/builtin-skills.ts:130) call ensureSkillFrontmatter once per tool on byte-identical copies, within one process.

Repro 1 — malformed frontmatter, 1 skill → 2 tool dirs

Team repo skills/malformed-skill/SKILL.md:

---
name: original-name
custom: [
---
# Body Heading

teamai pull --force:

⚠ Could not repair malformed frontmatter in malformed-skill/SKILL.md; leaving it unchanged   ← printed once
✔ [project] Synced 1 skills (1 new, 0 updated)
destination outcome
.claude/skills/malformed-skill/SKILL.md preserved
.cursor/skills/malformed-skill/SKILL.md rewritten — name: original-name and custom: [ destroyed, replaced by name: malformed-skill / description: Body Heading

Only one warning is printed, so the user believes both copies were left alone.

Repro 2 — cache aliasing

Two skills sharing the block --- / trigger: shared / ---, both missing name/description, × 2 tool dirs = 4 deployments:

✔ [project] Synced 2 skills (2 new, 0 updated)      ← zero warnings

Only .claude/skills/skill-a got its metadata. .claude/skill-b, .cursor/skill-a and .cursor/skill-b were all silently skipped — hasName && hasDescription read true off the poisoned cache entry — and are left permanently without name/description, i.e. undiscoverable in the marketplace.

This one predates the PR (it came in with #378), but it is what defeats the new guard, so it needs fixing here.

Suggested fix (verified)

-        const parsed = matter(raw);
+        const parsed = matter(raw, {});   // any options object disables gray-matter's cache read+write
         if (parsed.data === null || typeof parsed.data !== 'object' || Array.isArray(parsed.data)) {
             return { data: {}, valid: false, body, raw };
         }
-        data = parsed.data as Record<string, unknown>;
+        data = { ...(parsed.data as Record<string, unknown>) };

Rebuilt and re-ran both scenarios: repro 1 → both copies preserved, one warning each; repro 2 → all 4 deployments correctly completed. It also removes the unbounded matter.cache growth (every frontmatter block parsed during a run is currently retained for the process lifetime).

Related: the new tests pass only because each fixture block is parsed exactly once per test file — matter.cache is module-global within a Vitest worker. A second test reusing --- / just-a-scalar / --- would assert against the cached result rather than a real parse.


Other findings

typeof x === 'object' is not a mapping check — src/utils/frontmatter.ts:45. A YAML timestamp scalar parses to a Date: non-null, typeof object, not an array. Verified that --- / 2020-01-01 / --- + body passes the guard, gets name/description set on the Date, and matter.stringify drops the original value — the same data loss the PR prevents elsewhere.

Valid frontmatter is still lossy — src/resources/skills.ts:64. The repair path round-trips through matter.stringify, destroying YAML comments and normalizing quoting. Verified: a block with # keep me and allowed-tools: "Bash(git:*)" (missing description) comes back with the comment deleted and the value re-quoted as 'Bash(git:*)'. Before #378 the code appended lines and preserved the original text verbatim. Patching the missing keys into raw textually instead of re-serializing would fix this and make the malformed special case unnecessary.

valid conflates "absent" with "not a mapping" — src/utils/frontmatter.ts:8. It is false when there is no frontmatter at all, yet the doc reads "Whether the frontmatter parsed to a mapping/object". A caller writing the natural if (!valid) return; before checking raw would disable the injection path for files with no frontmatter. ensureSkillFrontmatter only works because it checks !raw first. Worth a tri-state, or a doc note that valid is only meaningful when raw !== ''.

Stale comment — src/resources/skills.ts:61-63 still says "if the original frontmatter had malformed YAML, splitFrontmatter yields an empty data, so the rebuilt block keeps only name/description and drops the bad content". The new early return made that path unreachable.

Test gaps — the scalar test (src/__tests__/skills.test.ts:851) doesn't assert the file was left byte-identical, unlike the malformed test right above it. And the Array.isArray branch added at frontmatter.ts:45 has no test at all, so deleting it would keep the suite green.

Docs — docs/usage-guide.md:354 and :429 still state that frontmatter completion is automatic with "no manual upkeep required"; malformed frontmatter now requires manual fixing. Per CLAUDE.md this needs a note in both docs/usage-guide.md and docs/usage-guide.zh-CN.md.

@jeff-r2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the detailed repro — confirmed. I pushed a follow-up that addresses all of the reported correctness issues:

  • disables gray-matter caching with matter(raw, {}) and clones parsed data;
  • accepts only plain YAML mappings (timestamps, arrays, and scalars are invalid);
  • appends missing fields textually so existing comments, quoting, key order, and line endings remain intact;
  • preserves malformed/scalar frontmatter byte-for-byte and warns;
  • documents the manual-repair behavior in both usage guides;
  • adds repeated malformed-block, cache-aliasing, timestamp/array, byte-preservation, and formatting-preservation tests.

I also reran the reported scenarios directly: repeated malformed blocks stay unchanged, identical valid blocks complete independently, and comments/quoting are preserved. Full suite passes: 178 files / 2,494 tests; typecheck passes.

@jeff-r2026
jeff-r2026 merged commit 0631400 into main Sep 1, 2026
7 checks passed
@jeff-r2026
jeff-r2026 deleted the codex/fix-frontmatter-object-validation branch September 11, 2026 09:15
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
…ect-validation

fix(frontmatter): preserve malformed skill metadata
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant