Skip to content

fix(memory): read and write front matter as data, never as code - #265

Merged
jddunn merged 2 commits into
masterfrom
fix/agentos-20a-item57-review
Oct 10, 2026
Merged

jddunn merged 2 commits into
masterfrom
fix/agentos-20a-item57-review

Conversation

@jddunn

@jddunn jddunn commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

Summary

Front matter is read and written as data. gray-matter reads a front-matter block in the language named after its opening line of dashes, and its own engine for js and javascript evaluates the block. Given a string to write front matter onto, it parses that string first. The library handed it Markdown files, persona files, wiki pages, and the bodies of memory traces and wiki pages, with those engines in place.

  • src/core/utils/frontMatter.ts is now the one module that calls gray-matter. readFrontMatter parses a YAML or JSON block into data. A block marked as JavaScript is not evaluated: it is taken off the content like any front matter and gives no data. writeFrontMatter writes a YAML block in front of a body it never reads, so a body that opens with a line of dashes is kept whole. Before, its first lines were read as a block of its own and lost from the content.
  • MarkdownLoader, MarkdownImporter, MarkdownExporter, ObsidianExporter, SoulLoader (loadSoul, loadSoulSync, parseSoul, renderSoulMarkdown) and the wiki's parsePage and serializePage go through it. A lint rule refuses an import of gray-matter anywhere else under src.
  • The document ingestion page and loadIsolated's TSDoc say what the isolated read leaves. A --max-old-space-size the process was started with overrides maxHeapMb whether it came from the command line or from NODE_OPTIONS: V8's options are the whole process's, whatever the worker's execArgv (the page said the worker starts with none of the caller's command-line options). The check behind maxExternalMb samples on a timer on the caller's event loop and does not cap. The answer is copied into the caller's heap. The page also says how a read ends when the worker fails in another way, that the package ships ES modules only, and that the worker is a thread of the caller's process and not a sandbox for code.

Linked issues

None.

Type of change

  • Bug fix
  • Documentation
  • Tests

How this was verified

CI on this branch: Test & Lint (build, lint with the new rule, type check and the whole suite), Batch-1 gated tests and the release dry run. New tests:

  • src/core/utils/__tests__/frontMatter.test.ts: YAML and JSON blocks read into data; a block marked js, javascript, JS or js gives no data and is not evaluated; a body that opens with a line of dashes, or with a block marked as JavaScript, is written whole, read back whole and not evaluated. Each case that must not evaluate also hands the same text to gray-matter with its own engines, which does evaluate it, so the case fails without this change.
  • loaders.test.ts: MarkdownLoader on a buffer whose front matter is marked as JavaScript.
  • WikiPageCodec.test.ts: a page whose body opens with such a block, through serializePage and parsePage.

Migration notes

None for YAML or JSON front matter. A block marked as JavaScript now gives no data, so write such front matter as YAML or JSON.

Checklist

  • Tests cover the changed behavior.
  • Docs are updated.
  • The title follows Conventional Commits, with ! before the colon for a change that breaks users (feat!: or feat(api)!:).
  • No secrets or private data are included.
  • Every automated review thread is settled (how).
  • I have read this change and can explain every line.

Summary by Sourcery

Read and write front matter strictly as data while preserving document bodies and documenting isolated-loader behavior accurately.

Bug Fixes:

  • Prevent front-matter content marked as JavaScript from being evaluated while preserving safe YAML and JSON metadata parsing.
  • Preserve bodies that begin with delimiter-like content when writing front matter across Markdown, wiki, persona, and memory workflows.

Enhancements:

  • Centralize all front-matter reads and writes behind shared data-only utilities and enforce that boundary with linting.
  • Clarify isolated document loading behavior, memory limits, worker failures, process-level V8 options, and its non-sandboxed execution model.

Documentation:

  • Update document-ingestion documentation to describe data-only front matter handling and the limits and failure modes of isolated loading.

Tests:

  • Add coverage for safe YAML/JSON parsing, non-evaluation of JavaScript front matter, preservation of delimiter-leading bodies, and affected Markdown and wiki integrations.

@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 13 billable files and costs up to $3.25.

  • Ask an admin to make reviews automatic

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Or wait 1 minute for your next included review.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Repository: framerslab/agentos/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Team
  • Run ID: 8bab618c-1995-4188-bc2b-aa9e2863a068

📥 Commits

Reviewing files that changed from the base of the PR and between 915acf3 and 3491e90.


📒 Files selected for processing (13)
  • docs/memory/MEMORY_DOCUMENT_INGESTION.md
  • eslint.config.js
  • src/cognition/memory/io/MarkdownExporter.ts
  • src/cognition/memory/io/MarkdownImporter.ts
  • src/cognition/memory/io/ObsidianExporter.ts
  • src/cognition/memory/io/ingestion/MarkdownLoader.ts
  • src/cognition/memory/io/ingestion/__tests__/loaders.test.ts
  • src/cognition/memory/io/ingestion/loadIsolated.ts
  • src/cognition/substrate/memory/wiki/WikiPageCodec.ts
  • src/cognition/substrate/memory/wiki/__tests__/WikiPageCodec.test.ts
  • src/cognition/substrate/personas/SoulLoader.ts
  • src/core/utils/__tests__/frontMatter.test.ts
  • src/core/utils/frontMatter.ts

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Oct 10, 2026

Copy link
Copy Markdown

Reviewer's Guide

The PR removes gray-matter's code-execution and body-reparsing hazards by funneling all front-matter access through a data-only utility, migrates every affected memory/document path to it, adds regression coverage and an import lint guard, and updates isolated-loader documentation to accurately describe its resource-limit and worker semantics.

Sequence diagram for isolated document loading limits

sequenceDiagram
    participant Caller
    participant Loader as loadIsolated
    participant Worker as Isolated worker
    participant DocumentLoader as Markdown/PDF/DOCX/Text loader

    Caller->>Loader: loadIsolated(kind, bytes, options)
    Loader->>Loader: copy bytes
    Loader->>Worker: start with resourceLimits and empty execArgv
    Worker->>DocumentLoader: read document
    DocumentLoader-->>Worker: content, metadata, format
    loop caller event loop timer
        Loader->>Worker: getHeapStatistics()
        Loader-->>Worker: end if timeout or sampled external memory exceeds bound
    end
    Worker-->>Loader: answer or worker error
    Loader-->>Caller: copied result or rejection
Loading

Flow diagram for front matter parsing behavior

flowchart TD
    Start[Read document text] --> Delimiter{Front matter delimiter?}
    Delimiter -->|YAML or JSON| Parse[Parse as data]
    Delimiter -->|JavaScript| Drop[Remove block without evaluating]
    Delimiter -->|None| Body[Keep full text as body]
    Parse --> Result[Return data and remaining body]
    Drop --> Result
    Body --> Result
    Write[Write front matter] --> Unparsed[Pass body as content without reparsing]
    Unparsed --> Serialized[Return YAML block plus unchanged body]
Loading

File-Level Changes

Change Details Files
Centralize front-matter parsing and serialization behind data-only wrappers.
  • Configure gray-matter reads so JavaScript-marked blocks are removed without evaluation while YAML and JSON remain supported.
  • Serialize with an explicit content field so bodies are never reparsed, preserving bodies that begin with delimiters or JavaScript-marked blocks.
  • Add a lint restriction preventing gray-matter imports outside the wrapper module.
src/core/utils/frontMatter.ts
eslint.config.js
src/core/utils/__tests__/frontMatter.test.ts
Migrate document, persona, and wiki memory paths to the safe front-matter utilities.
  • Replace direct gray-matter reads and writes in Markdown import/export, Obsidian export, Markdown loading, soul loading/rendering, and wiki page codecs.
  • Document that JavaScript front matter is discarded without metadata and never executed.
  • Preserve wiki and exported content verbatim when it begins with front matter-like delimiters.
src/cognition/memory/io/MarkdownExporter.ts
src/cognition/memory/io/MarkdownImporter.ts
src/cognition/memory/io/ObsidianExporter.ts
src/cognition/memory/io/ingestion/MarkdownLoader.ts
src/cognition/memory/io/ingestion/__tests__/loaders.test.ts
src/cognition/substrate/memory/wiki/WikiPageCodec.ts
src/cognition/substrate/memory/wiki/__tests__/WikiPageCodec.test.ts
src/cognition/substrate/personas/SoulLoader.ts
Clarify isolated document-loading resource, process, and failure semantics.
  • Document that process-wide V8 heap options, including NODE_OPTIONS and command-line max-old-space-size, override worker heap limits.
  • Clarify that external-memory monitoring samples on the caller event loop and is not a hard cap.
  • Describe worker failure behavior, copied results, ES-module packaging requirements, and the worker's lack of sandbox isolation.
  • Document timeout validation and the worker-thread entry-file requirement.
src/cognition/memory/io/ingestion/loadIsolated.ts
docs/memory/MEMORY_DOCUMENT_INGESTION.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@jddunn
jddunn marked this pull request as ready for review October 10, 2026 19:16
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 10, 2026 19:16
@sourcery-ai

sourcery-ai Bot commented Oct 10, 2026

Copy link
Copy Markdown

Sorry @jddunn, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 9 hours and 22 minutes by commenting @sourcery-ai review. Upgrade to get a review now.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-10T19:18:02.602655Z 3491e90 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Read and write front matter without evaluating JavaScript

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Prevent JavaScript-marked front matter from executing while retaining YAML and JSON metadata
 parsing.
• Preserve delimiter-leading bodies when exporting memory traces, wiki pages, and personas.
• Centralize front-matter handling and clarify isolated document loading limits.
Diagram

graph TD
  A["Document inputs"] --> B["Read workflows"] --> D["Front matter utility"] --> E[["gray-matter"]]
  C["Memory bodies"] --> F["Write workflows"] --> D
  D --> G["Data and documents"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Replace gray-matter with a YAML/JSON-only parser
  • ➕ Removes gray-matter's executable engines from the parsing boundary entirely.
  • ➖ Requires recreating delimiter parsing and serialization behavior, increasing compatibility risk and review scope.

Recommendation: Keep the shared wrapper: it blocks the executable engine and avoids reparsing bodies while preserving existing YAML/JSON handling. A parser replacement is worth considering only if the project later needs a stricter front-matter format policy.

Files changed (13) +314 / -38

Bug fix (7) +119 / -23
MarkdownExporter.tsPreserve trace content during Markdown export +4/-3

Preserve trace content during Markdown export

• Routes front-matter serialization through the shared writer so delimiter-leading trace content is not parsed before export.

src/cognition/memory/io/MarkdownExporter.ts

MarkdownImporter.tsRead imported Markdown metadata without executing code +4/-3

Read imported Markdown metadata without executing code

• Uses the shared reader for imported files, discarding JavaScript-marked front matter rather than evaluating it while retaining parse-error reporting.

src/cognition/memory/io/MarkdownImporter.ts

ObsidianExporter.tsPreserve Obsidian export bodies during serialization +3/-2

Preserve Obsidian export bodies during serialization

• Uses the shared writer to prepend metadata without parsing the trace body and its appended tags or wiki links.

src/cognition/memory/io/ObsidianExporter.ts

MarkdownLoader.tsDisable executable front matter in Markdown ingestion +10/-3

Disable executable front matter in Markdown ingestion

• Reads metadata through the shared utility. JavaScript-marked blocks contribute no metadata, leaving the existing heading-based title fallback available.

src/cognition/memory/io/ingestion/MarkdownLoader.ts

WikiPageCodec.tsUse safe front-matter handling for wiki pages +11/-5

Use safe front-matter handling for wiki pages

• Routes page parsing and serialization through the shared utility, preventing JavaScript execution on reads and preserving delimiter-leading page bodies on writes.

src/cognition/substrate/memory/wiki/WikiPageCodec.ts

SoulLoader.tsSafeguard persona front-matter reads and writes +9/-7

Safeguard persona front-matter reads and writes

• Switches asynchronous, synchronous, and inline persona parsing to the shared reader. Persona rendering uses the shared writer to preserve body text without parsing it.

src/cognition/substrate/personas/SoulLoader.ts

frontMatter.tsIntroduce shared data-only front-matter utility +78/-0

Introduce shared data-only front-matter utility

• Adds a reader that replaces gray-matter's JavaScript engine with a non-evaluating handler and a writer that passes body content without first parsing it. Explicit read options also avoid gray-matter's default whole-text cache.

src/core/utils/frontMatter.ts

Tests (3) +154 / -0
loaders.test.tsTest JavaScript-marked Markdown ingestion +25/-0

Test JavaScript-marked Markdown ingestion

• Verifies that loading a buffer neither executes its front matter nor uses it as metadata, and that the body and heading-derived title remain correct.

src/cognition/memory/io/ingestion/tests/loaders.test.ts

WikiPageCodec.test.tsTest wiki body preservation and non-evaluation +32/-0

Test wiki body preservation and non-evaluation

• Checks that a JavaScript-marked block in a page body survives serialization and parsing, while the same block as file front matter supplies no data or executable behavior.

src/cognition/substrate/memory/wiki/tests/WikiPageCodec.test.ts

frontMatter.test.tsCover data-only parsing and lossless writing +97/-0

Cover data-only parsing and lossless writing

• Tests YAML and JSON reads, multiple JavaScript language markers, and bodies beginning with delimiter-like text. Contrasts non-evaluation with gray-matter's default behavior and checks write/read round trips.

src/core/utils/tests/frontMatter.test.ts

Documentation (2) +27 / -15
MEMORY_DOCUMENT_INGESTION.mdDocument safe front matter and isolated-load boundaries +8/-6

Document safe front matter and isolated-load boundaries

• Explains that JavaScript-marked Markdown front matter is discarded without execution. Clarifies worker failure modes, copied results, memory-limit caveats, process-wide V8 options, ES-module packaging, and why the worker is not a sandbox.

docs/memory/MEMORY_DOCUMENT_INGESTION.md

loadIsolated.tsClarify isolated loader resource-limit semantics +19/-9

Clarify isolated loader resource-limit semantics

• Updates TSDoc to distinguish sampled external-memory checks from hard caps and to explain process-wide V8 options and the worker's non-sandboxed nature. Runtime behavior is unchanged.

src/cognition/memory/io/ingestion/loadIsolated.ts

Other (1) +14 / -0
eslint.config.jsRestrict direct gray-matter imports in source +14/-0

Restrict direct gray-matter imports in source

• Adds a lint rule directing production TypeScript modules to use the shared front-matter utility instead of importing gray-matter directly.

eslint.config.js

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (1) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Trace file safety lacks integration tests 📘 Rule violation ⚙ Maintainability
Description
The new writeFrontMatter test checks a JavaScript-marked body only by calling the helper directly;
it does not export a stored trace or import a file through the changed memory I/O paths. Existing
I/O tests use ordinary trace content and YAML fixtures, so they do not check whether those paths
preserve a delimiter-leading body or avoid evaluating JavaScript-marked front matter.
Code

src/core/utils/tests/frontMatter.test.ts[R81-84]

+  it('evaluates no body that opens with a block marked as JavaScript, and keeps it whole', () => {
+    const body = fileMarked('js');
+
+    const written = writeFrontMatter(body, { id: 'trace-2' });
Evidence
Rule 5 requires integration tests for changed observable behavior. The new regression test calls the
helper directly, while the production exporter and importer reach it through trace storage and
filesystem I/O; the existing I/O tests cover ordinary content rather than the changed cases.

AGENTS.md: Test Observable Behavior Through Real Paths: AGENTS.md: Test Observable Behavior Through Real Paths
src/core/utils/tests/frontMatter.test.ts[81-95]
src/cognition/memory/io/MarkdownExporter.ts[105-119]
src/cognition/memory/io/MarkdownImporter.ts[154-178]
src/cognition/memory/io/tests/io.test.ts[363-449]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The helper regression tests do not exercise the changed memory trace export and import paths with JavaScript-marked front matter.
## Fix Focus Areas
- src/cognition/memory/io/__tests__/io.test.ts[363-449]
- src/core/utils/__tests__/frontMatter.test.ts[81-95]
## Recommended Fix
Add I/O integration cases that export a stored trace whose body begins with a JavaScript-marked block and import a file with JavaScript-marked front matter. Assert the exported body is preserved and the imported block is neither evaluated nor used as metadata.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

2. Empty metadata lets a dashed body be misread 🐞 Bug ≡ Correctness
Description
writeFrontMatter hands { content: body } to matter.stringify, and gray-matter writes no block
at all when the data serializes to {}. Its output is then just the body, so a body that opens with
--- is read back by readFrontMatter as front matter: its first lines are cut from the content,
which is the loss this helper's TSDoc says can't happen.
Code

src/core/utils/frontMatter.ts[R76-78]

+export function writeFrontMatter(body: string, data: Record<string, unknown>): string {
+  return matter.stringify({ content: body }, data);
+}
Evidence
gray-matter's stringify only adds the --- block when the dumped data isn't {}. Today's callers
always pass at least one field (id in the exporters and the wiki, name in renderSoulMarkdown),
so none of them hits this yet. The helper is now the one place for all front-matter writes, though,
and its doc promises without condition that the body is kept whole. The test only covers non-empty
data.

src/core/utils/frontMatter.ts[57-78]
src/core/utils/tests/frontMatter.test.ts[70-79]
src/cognition/substrate/personas/SoulLoader.ts[400-447]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`writeFrontMatter` relies on gray-matter, which writes no front-matter block when the data is empty. A body that starts with `---` is then read back as front matter and loses its first lines.
## Fix Focus Areas
- src/core/utils/frontMatter.ts[76-78]
- src/core/utils/__tests__/frontMatter.test.ts[70-79]
## Recommended Fix
When `Object.keys(data).length === 0`, return `'---\n---\n' + body` (or `'---\n{}\n---\n'`), ending in a newline, so there is always a block in front of the body. Otherwise keep calling `matter.stringify`. Add a test that `writeFrontMatter('---\nA rule\n', {})` round-trips through `readFrontMatter` with the body unchanged.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can copy the agent prompt from any finding and feed it to your IDE agent

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread src/core/utils/frontMatter.ts Resolved
@jddunn
jddunn merged commit af3801b into master Oct 10, 2026
8 checks passed
@jddunn
jddunn deleted the fix/agentos-20a-item57-review branch October 10, 2026 19:19
github-actions Bot pushed a commit that referenced this pull request Oct 10, 2026
## [0.13.36](v0.13.35...v0.13.36) (2026-10-10)

### fix

* **memory:** read and write front matter as data, never as code (#265) ([af3801b](af3801b))
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