Skip to content

feat: support page-level agent-only content (DOCSTOOLS-6733) - #2391

Merged
kadymov merged 1 commit into
masterfrom
codex/DOCSTOOLS-6733-page-audience
Nov 18, 2026
Merged

kadymov merged 1 commit into
masterfrom
codex/DOCSTOOLS-6733-page-audience

Conversation

@kadymov

@kadymov kadymov commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

What changed

Add page-level visibility: agent in toc.yaml for DOCSTOOLS-6733. The restriction inherits through nested sections and included TOCs. A document referenced from both common and agent sections fails the build.

Markdown builds preserve sources and write generated pageAudience: agent metadata. HTML navigation, pages, sitemap and human LLMS files omit agent pages. Agent LLMS files include them and rewrite links to the agent representation. Visible human links to agent pages produce a diagnostic.

Task: https://st.yandex-team.ru/DOCSTOOLS-6733

Related schema: diplodoc-platform/ajv#91

User documentation: diplodoc-platform/docs#369

Dynamic serving requires the corresponding Viewer changes and rebuilding documentation. Existing block-level audience behavior is preserved.

Validation

  • Full unit suite passed in the commit hook.
  • Full integration suite: 286 passed, 1 skipped, 1 todo across 54 files.
  • Typecheck, build, lint and formatting passed (lint reports existing warnings).
  • End-to-end fixtures cover inherited/include visibility, multilingual navigation, human/static output, agent corpus, conflicts and agent links.
  • Runtime work adds a cached TOC audience index per worker and constant-time page lookup. Agent corpus generation adds work proportional to its content; there are no new per-link filesystem reads or network calls.

No package versions or dependencies changed. Release and downstream production behavior have not been verified.

@kadymov
kadymov force-pushed the codex/DOCSTOOLS-6733-page-audience branch from 958c9b4 to bda3aff Compare November 13, 2026 08:48
@kadymov
kadymov marked this pull request as ready for review November 13, 2026 09:51
@kadymov
kadymov requested review from a team and diplodoc-bot as code owners November 13, 2026 09:51
@kadymov
kadymov requested review from reazy015 and separatrixxx and removed request for a team November 13, 2026 09:51
@kadymov
kadymov force-pushed the codex/DOCSTOOLS-6733-page-audience branch from b534453 to 3cf886c Compare November 17, 2026 08:55
@kadymov
kadymov requested a review from goldserg November 17, 2026 10:12

@goldserg goldserg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: page-level agent-only content (DOCSTOOLS-6733)

Reviewed together with the Viewer side (internal PR 16999226). The TOC-level audience index, the inheritance rules and the separation of human/agent artifacts look well designed, and the e2e coverage in tests/e2e/page-audience.spec.ts is genuinely good — it checks navigation, search export, sitemap, single-page and the agent corpora in one place.

A few things I'd like to resolve before merge.

1. collectPageAudiences mutates the TOC it is given

src/core/toc/audience.ts:

const agentOnly = inheritedAgent || item.visibility === 'agent';
if (agentOnly) {
    item.visibility = 'agent';
}

The function is documented as "resolves page audiences", but it also writes inherited visibility back into every descendant item. That write is load-bearing — output-html/index.ts and singlepage/index.ts later read item.visibility / toc.visibility directly and depend on the inherited value being materialised.

Two concerns:

  • It is reachable from TocService.audience(), which is a lazily-computed getter called from link resolution (resolveAgentPageLink), the sitemap filter and processEntry. A getter that mutates shared state on first call is easy to misuse later.
  • The cache key is this.relations.revision. If relations.revision changes but the TOC objects are reused, visit() runs again over already-mutated items — idempotent today, but only because the write is = 'agent'.

Suggestion: either rename to make the mutation explicit (resolvePageAudiences) and document that it finalises visibility on the tree, or split the propagation into an explicit pass run once from init(), leaving audience() as a pure lookup. The existing test even asserts the mutation (expect(input.items?.[0].items?.[0].visibility).toBe('agent')), so the intent is clearly deliberate — it just isn't stated anywhere a future reader would look.

2. TocService.init triggers validation via paths[0]

async init(paths: NormalizedPath[]) {
    for (const path of paths) {
        await this.load(path);
    }

    // Validate conflicts before writing any audience-dependent build artifacts.
    this.audience(paths[0]);

Using paths[0] purely to force the side effect is fragile:

  • if paths is empty, paths[0] is undefined and audience(undefined) is called — it happens to work (the Map lookup misses), but it is accidental;
  • the intent ("build the index now so conflicts throw early") is only visible in the comment.

Suggest an explicit method, e.g. this.validateAudiences() or this.audienceIndex(), that does not pretend to query a specific page.

3. everySeries + fullLimitReached is hard to follow

In renderFull, the loop was converted from for..of to everySeries so that static artifacts keep being written after the corpus size limit is hit:

if (!body || fullLimitReached) {
    return true;
}
...
fullLimitReached = true;
return staticAgent;

The control flow now encodes three different things in one boolean return (continue iterating / stop iterating / "keep going but only for the side effect"), plus an outer mutable flag. It took me a few passes to convince myself that the dynamic corpus really does stop growing after the limit while static files continue.

The behaviour looks correct and the test writes every linked static target once even when the corpus limit is %s bytes covers both limits. But I'd suggest either a short comment spelling out the three states, or splitting into two passes (collect bodies for static output; then accumulate into the corpus until the limit). Given llms-full is already a known memory-sensitive path, clarity here has real value.

4. URLSearchParams.size — confirm the supported Node range

resolveAgentPageLink uses search.size:

const querySuffix = search.size ? `?${search}` : '';

URLSearchParams.prototype.size landed in Node 19.8 / 18.16. package.json declares "node": ">=24", so this is fine for the CLI itself — just flagging it because this helper is in a file that gets bundled, and if anything here is ever consumed under an older runtime it fails with undefined (falsy) rather than loudly. If the >=24 floor is firm, ignore this.

5. filterAgentYaml — Object.defineProperty instead of assignment

Object.defineProperty(result, key, {
    value: filterAgentYaml(item, rewrite, seen),
    enumerable: true,
    configurable: true,
    writable: true,
});

This is equivalent to result[key] = ... for every case except prototype-polluting keys (__proto__), which I assume is exactly the point — input is arbitrary user YAML. If so, please add a one-line comment saying so; otherwise the next reader will "simplify" it back to assignment and silently reintroduce the issue.

The cycle handling via seen WeakMap is correct and the test with recursive: &loop {self: *loop} covers it nicely.

6. Minor

  • src/commands/build/index.ts: outputFormat === 'html' compares against a string literal while OutputFormat.html is used elsewhere in the same PR (llms/index.ts). Worth using the enum consistently.
  • page-audience-links.ts: the candidate list (.md, .yaml, index.md, index.yaml) is duplicated almost verbatim in resolveAgentPageLink in llms/index.ts. Two copies of the same resolution rule will drift — consider extracting a shared helper.
  • README says "Conflicting shared/agent references to the same document fail the build", which matches collectPageAudiences. Good — but the error message itself (Conflicting visibility for ${path}: common and agent TOC references.) does not say which TOCs conflict. For a large docs project that is the first question an author will ask. Including both TOC paths would make it actionable.

Verification

I reviewed the diff only; I did not run the build or the test suite locally. The stated validation (full unit suite, 286 integration tests, typecheck/build/lint) looks appropriate for the change size.

Since this PR and the Viewer PR must ship together with matching artifacts, please make sure the end-to-end path — build a real project with an agent section, serve it through the updated Viewer — is exercised before release. Both PR descriptions currently say production behaviour has not been verified.

@kadymov

kadymov commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Что не стал править:

  • CLI №4 и №7. URLSearchParams.size поддерживается заявленным Node.js >=24. Диагностика и генерация уже используют общий resolvePageTarget.

Review: page-level agent-only content (DOCSTOOLS-6733)

Reviewed together with the Viewer side (internal PR 16999226). The TOC-level audience index, the inheritance rules and the separation of human/agent artifacts look well designed, and the e2e coverage in tests/e2e/page-audience.spec.ts is genuinely good — it checks navigation, search export, sitemap, single-page and the agent corpora in one place.

A few things I'd like to resolve before merge.

1. collectPageAudiences mutates the TOC it is given

src/core/toc/audience.ts:

const agentOnly = inheritedAgent || item.visibility === 'agent';
if (agentOnly) {
item.visibility = 'agent';
}
The function is documented as "resolves page audiences", but it also writes inherited visibility back into every descendant item. That write is load-bearing — output-html/index.ts and singlepage/index.ts later read item.visibility / toc.visibility directly and depend on the inherited value being materialised.

Two concerns:

  • It is reachable from TocService.audience(), which is a lazily-computed getter called from link resolution (resolveAgentPageLink), the sitemap filter and processEntry. A getter that mutates shared state on first call is easy to misuse later.
  • The cache key is this.relations.revision. If relations.revision changes but the TOC objects are reused, visit() runs again over already-mutated items — idempotent today, but only because the write is = 'agent'.

Suggestion: either rename to make the mutation explicit (resolvePageAudiences) and document that it finalises visibility on the tree, or split the propagation into an explicit pass run once from init(), leaving audience() as a pure lookup. The existing test even asserts the mutation (expect(input.items?.[0].items?.[0].visibility).toBe('agent')), so the intent is clearly deliberate — it just isn't stated anywhere a future reader would look.

2. TocService.init triggers validation via paths[0]

async init(paths: NormalizedPath[]) {
for (const path of paths) {
await this.load(path);
}

// Validate conflicts before writing any audience-dependent build artifacts.
this.audience(paths[0]);

Using paths[0] purely to force the side effect is fragile:

  • if paths is empty, paths[0] is undefined and audience(undefined) is called — it happens to work (the Map lookup misses), but it is accidental;
  • the intent ("build the index now so conflicts throw early") is only visible in the comment.

Suggest an explicit method, e.g. this.validateAudiences() or this.audienceIndex(), that does not pretend to query a specific page.

3. everySeries + fullLimitReached is hard to follow

In renderFull, the loop was converted from for..of to everySeries so that static artifacts keep being written after the corpus size limit is hit:

if (!body || fullLimitReached) {
return true;
}
...
fullLimitReached = true;
return staticAgent;
The control flow now encodes three different things in one boolean return (continue iterating / stop iterating / "keep going but only for the side effect"), plus an outer mutable flag. It took me a few passes to convince myself that the dynamic corpus really does stop growing after the limit while static files continue.

The behaviour looks correct and the test writes every linked static target once even when the corpus limit is %s bytes covers both limits. But I'd suggest either a short comment spelling out the three states, or splitting into two passes (collect bodies for static output; then accumulate into the corpus until the limit). Given llms-full is already a known memory-sensitive path, clarity here has real value.

4. URLSearchParams.size — confirm the supported Node range

resolveAgentPageLink uses search.size:

const querySuffix = search.size ? ?${search} : '';
URLSearchParams.prototype.size landed in Node 19.8 / 18.16. package.json declares "node": ">=24", so this is fine for the CLI itself — just flagging it because this helper is in a file that gets bundled, and if anything here is ever consumed under an older runtime it fails with undefined (falsy) rather than loudly. If the >=24 floor is firm, ignore this.

5. filterAgentYaml — Object.defineProperty instead of assignment

Object.defineProperty(result, key, {
value: filterAgentYaml(item, rewrite, seen),
enumerable: true,
configurable: true,
writable: true,
});
This is equivalent to result[key] = ... for every case except prototype-polluting keys (__proto__), which I assume is exactly the point — input is arbitrary user YAML. If so, please add a one-line comment saying so; otherwise the next reader will "simplify" it back to assignment and silently reintroduce the issue.

The cycle handling via seen WeakMap is correct and the test with recursive: &loop {self: *loop} covers it nicely.

6. Minor

  • src/commands/build/index.ts: outputFormat === 'html' compares against a string literal while OutputFormat.html is used elsewhere in the same PR (llms/index.ts). Worth using the enum consistently.
  • page-audience-links.ts: the candidate list (.md, .yaml, index.md, index.yaml) is duplicated almost verbatim in resolveAgentPageLink in llms/index.ts. Two copies of the same resolution rule will drift — consider extracting a shared helper.
  • README says "Conflicting shared/agent references to the same document fail the build", which matches collectPageAudiences. Good — but the error message itself (Conflicting visibility for ${path}: common and agent TOC references.) does not say which TOCs conflict. For a large docs project that is the first question an author will ask. Including both TOC paths would make it actionable.

Verification

I reviewed the diff only; I did not run the build or the test suite locally. The stated validation (full unit suite, 286 integration tests, typecheck/build/lint) looks appropriate for the change size.

Since this PR and the Viewer PR must ship together with matching artifacts, please make sure the end-to-end path — build a real project with an agent section, serve it through the updated Viewer — is exercised before release. Both PR descriptions currently say production behaviour has not been verified.

That I didn't edit:

@goldserg goldserg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Проверил исправления — все технические замечания закрыты:

Исправлено:

  1. ✅ collectPageAudiences → resolvePageAudiences с явным JSDoc о мутации
  2. ✅ TocService.init теперь вызывает явный validateAudiences() вместо audience(paths[0])
  3. ✅ everySeries + fullLimitReached — добавлен комментарий про три состояния
  4. ✅ filterAgentYaml — добавлен комментарий про защиту от __proto__
  5. ✅ Все три мелочи (#6): enum OutputFormat.html, общий resolvePageTarget, улучшенное сообщение об ошибке конфликта

Не исправлено (по решению автора):

  • #4 (URLSearchParams.size) — автор подтвердил, что package.json декларирует "node": ">=24", что покрывает .size (Node 19.8+). Если бандл не используется под старым runtime — всё ок.
  • #7 (end-to-end verification) — остаётся рекомендацией перед релизом, как указано в описании PR.

Технически PR готов к влитию. Рекомендую провести end-to-end проверку на реальном проекте с agent-разделом перед релизом, как указано в описании обоих PR (Viewer + CLI).

@kadymov
kadymov force-pushed the codex/DOCSTOOLS-6733-page-audience branch from b609750 to 08bd68a Compare November 18, 2026 09:18
@sonarqubecloud

Copy link
Copy Markdown

@kadymov
kadymov merged commit 14f8520 into master Nov 18, 2026
17 checks passed
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.

2 participants