Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/patch-canonical-report-rendering.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

133 changes: 133 additions & 0 deletions .github/skills/issue-markdown/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
---
name: issue-markdown
description: Build and refactor issue, comment, and review bodies in actions/setup/js using typed report trees and a single publication render.
---

# Issue and comment Markdown

Use this skill when generating or changing Markdown published to issues, comments,
or reviews, especially in `actions/setup/js/`. Build a `Report` tree first; render
only the complete document. Do not assemble Markdown using interpolation,
concatenation, `body +=`, or arrays of Markdown strings joined with newlines.
Parsing an assembled string afterward is not a tree-first refactor.

## Find publication paths

Search production `.cjs` files for `issues.create`, `issues.update`,
`createComment`, `updateComment`, `createReview`, `createReplyForReviewComment`,
and GraphQL body variables. Trace each body back through shared helpers, fallback
comments, retries, staged previews, and append/prepend/replace-island updates.
Exclude test fixtures, HTTP payload assembly, and step-summary-only output.
Jira ADF text is not Markdown: preserve its literal entities, Unicode, and
paragraphs instead of routing it through the Markdown parser or renderer.

## Use the existing tree

`actions/setup/js/report_ast.cjs` defines `Report`, `ReportBlock`, and `ReportInline`.
Use JSDoc annotations so `npm run typecheck` verifies node kinds:

```javascript
/** @type {import("./report_ast.cjs").Report} */
const report = {
type: "report",
title: "Workflow result",
children: [
{
type: "paragraph",
agentTainted: false,
children: [
{ type: "text", value: "Created related issue: ", agentTainted: false },
{ type: "issue_reference", number: String(issue.number), agentTainted: false },
],
},
{ type: "code_block", language: "text", value: diagnostic, agentTainted: true },
],
};
```

Use `heading`, `paragraph`, `list`, `table`, `details`, `quote`, `alert`,
`separator`, `code_block`, and typed inline nodes instead of Markdown punctuation.
GitHub `[!NOTE]`, `[!TIP]`, `[!IMPORTANT]`, `[!WARNING]`, and `[!CAUTION]`
map to `alert` nodes with the matching `kind`; the renderer emits their markers.
Keep alerts separate rather than nesting them inside another alert, which GitHub
does not support. Preserve supported `<sub>` formatting in details summaries.
Use `xml_marker`, `json_marker`, `expiration`, and `closing_reference` for machine
metadata and closing links. Preserve `xml_marker.compact` for identifiers whose
exact spelling is used by cleanup. Use `review_marker` for the durable,
URI-encoded review caller reference; keep the authoritative marker last.
Dynamic labels, paths, errors, and identifiers belong
in text/code nodes; link destinations belong in `link.url`.

Import existing agent/user Markdown with `parseReportMarkdown`, specifying
`agentTainted: true`, the correct `allowedMentions`, and the existing heading and
metadata policy. Parse configured templates before scalar substitution using
`context`; use typed inline/block slots for inserted nodes. Never interpolate
untrusted values into a template before parsing it. A literal code fence in
imported content must not swallow attribution or adjacent generated blocks.

For managed comment memory, set `code_block.language` to
`gh-aw-comment-memory:<id>` and `fenceLength: 6`; rendering lengthens the fence
past embedded backticks. Do not construct or slice fences by hand.

## Compose shared attribution

Use the typed variants instead of rendering a helper and reparsing its output:

| Purpose | Tree-first API |
| --- | --- |
| Generated attribution and guard notices | `buildGeneratedFooterBlocks` / `assembleReportBodyParts` in `markdown_body_helpers.cjs` |
| Deferred footer templates and diagnostic sections | `buildFooterBlocks(getFooterMessageParts(context))` in `messages_footer.cjs` |
| Configured policy footer | `getBodyFooterBlocks` or `appendConfiguredReportFooter` |
| Detection warning | `getDetectionCautionBlocks` |
| Failure-comment attribution | `getFooterAgentFailureCommentBlocks` |
| Authoritative execution metadata | `appendReportExecutionProvenance` |

Keep custom templates and their scalar context separate until composition.
Headers and footers may jointly open/close `<details>`; use
`buildIssueBodyReport` to parse these wrappers together around body slots.
Allocate unique slot names against both source text and previously allocated
slots, and reject wrappers that swallow slots inside code fences.
Internal framework notes carried between handlers use non-JSON-forgeable Symbols
such as `COMMENT_PREAMBLE` and `ISSUE_BODY_SUFFIX`, never agent-settable flags.

## Preserve publication contracts

Framework-authored nodes use `agentTainted: false`; agent-owned descendants retain
their taint even inside framework wrappers. Keep required footer diagnostics,
metadata, and policy text protected during size fitting. Do not mark an entire
agent body trusted to keep it from being shortened.

For attributed safe-output issues and comments, use `buildIssueBodyReport` in
`issue_body.cjs`; it accepts Markdown or typed body blocks and retains configured
wrappers, attribution, expiration, and execution provenance. Comment callers set
the appropriate `itemType` and `workflowIdMarker: false`. Pass the original
workflow `runUrl` when the target repository differs from the execution repository.
Fallback issues must import the original agent body and compose recovery nodes,
not reparse an already assembled or rendered PR/discussion description.

For other issue producers, pass a typed report to
`renderIssueParameters`/`createReportIssue` in `issue_report.cjs`, preserving the
existing authentication and retry boundary. `buildIssueReport` accepts typed
blocks as well as imported Markdown. For comments, render the complete tree with
`renderSizedReport` from `report_size.cjs` and pass its body to the existing API.
Do not render fragments and concatenate or reparse them. Keep one logical render
boundary, including metadata and trusted footers in its size budget.
`renderSizedReport` trims trailing whitespace automatically and measures the
publication body against the exact `maxLength`. Do not trim its result or reserve
an extra character for a terminal newline. Low-level `renderReport` retains its
terminal newline for Markdown serialization. Never truncate rendered Markdown
or trusted policy text to fit.

## Validate the migration

Preserve footer on/off behavior, marker identity and order, mention/link limits,
expiration, cross-repository attribution, structured state recovery, managed
memory extraction, review fallbacks, and append/prepend/island semantics.
Assert tree shape as well as rendered output. Cover hostile backticks and HTML
delimiters, Unicode, escaped table cells, and the exact publication size limit.
Update formatting expectations only for intentional canonical rendering, not to
hide lost content or metadata.

Run the matching Vitest suites from `actions/setup/js`, `npm run typecheck`,
and the repository JavaScript formatting/lint gates. Follow the developer skill
for final repository validation and publication.
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ When the relevant skill is not obvious, first discover candidates locally and th
- Query helpers for issues/PRs/workflows/discussions/labels → matching `.github/skills/github-*-query/SKILL.md`
- Security-focused reviews of agentic workflow changes (compile/scans/audit/optimization) → `.github/skills/review-agentic-workflows/SKILL.md`
- Doc-writing conventions → `.github/skills/documentation/SKILL.md`
- Issue/comment Markdown construction and refactoring → `.github/skills/issue-markdown/SKILL.md`
- Visual changes to the docs site or landing page (layout, widths, spacing, colour, header nav) → `.github/skills/docs-design/SKILL.md`
- Reviewing or writing `git`/`gh`/remote operations against checkouts (per-checkout credentials, sparse/shallow monorepos, safe-outputs MCP runs without credentials) → `.github/skills/checkout-credential-review/SKILL.md`
- Authoring, validating, or debugging canvas extensions (loopback servers, actions, iframe rendering, state model, theme tokens) → `.github/skills/create-canvas/SKILL.md`
Expand Down
101 changes: 13 additions & 88 deletions actions/setup/js/add_comment.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,27 @@
* @typedef {import('./types/handler-factory').HandlerFactoryFunction} HandlerFactoryFunction
*/

const { assembleMarkdownBodyParts } = require("./markdown_body_helpers.cjs");
const { appendExecutionProvenance } = require("./execution_provenance.cjs");
const { getBodyFooterMessage } = require("./messages_footer.cjs");
const { buildIssueBodyReport, COMMENT_PREAMBLE } = require("./issue_body.cjs");
Comment thread
pelikhan marked this conversation as resolved.
Resolved
const { parseReportMarkdown } = require("./report_markdown.cjs");
Comment thread
pelikhan marked this conversation as resolved.
Resolved
const { stripExecutionProvenance } = require("./execution_provenance.cjs");
const { generateWorkflowCallIdMarker, matchesWorkflowId } = require("./generate_footer.cjs");
const { getRepositoryUrl } = require("./get_repository_url.cjs");
const { replaceTemporaryIdReferences, resolveSafeOutputIssueTarget } = require("./temporary_id.cjs");
const { getTrackerID } = require("./get_tracker_id.cjs");
const { getErrorMessage } = require("./error_helpers.cjs");
const { parseBoolTemplatable, parseIntTemplatable } = require("./templatable.cjs");
const { resolveTarget, isStagedMode } = require("./safe_output_helpers.cjs");
const { resolveTargetRepoConfig, resolveAndValidateRepo } = require("./repo_helpers.cjs");
const { createAuthenticatedGitHubClient } = require("./handler_auth.cjs");
const { getMissingInfoSections } = require("./missing_messages_helper.cjs");
const { getMessages } = require("./messages_core.cjs");
const { getBodyHeader, getDisclosureHeader } = require("./messages_header.cjs");
const { sanitizeContent } = require("./sanitize_content.cjs");
const { MAX_COMMENT_LENGTH, MAX_COMMENT_INPUT_LENGTH, MAX_MENTIONS, MAX_LINKS, enforceCommentLimits } = require("./comment_limit_helpers.cjs");
const { fitMarkdownBody } = require("./report_size.cjs");
const { renderSizedReport } = require("./report_size.cjs");
const { createDiscussionComment, resolveTopLevelDiscussionCommentId } = require("./github_api_helpers.cjs");
const { logStagedPreviewInfo } = require("./staged_preview.cjs");
const { ERR_CONFIG, ERR_NOT_FOUND } = require("./error_codes.cjs");
const { isPayloadUserBot } = require("./resolve_mentions.cjs");
const { getMentionsGithubClient, resolveMentionsForItem } = require("./resolve_mentions_from_payload.cjs");
const { buildWorkflowRunUrl } = require("./workflow_metadata_helpers.cjs");
const { generateHistoryUrl } = require("./generate_history_link.cjs");
const { resolveInvocationContext } = require("./invocation_context_helpers.cjs");

/** @type {string} Safe output type handled by this module */
Expand Down Expand Up @@ -829,92 +825,21 @@ async function main(config = {}) {
}

const linkBody = processedBody;
const workflowName = process.env.GH_AW_WORKFLOW_NAME || "Workflow";
const runUrl = buildWorkflowRunUrl(context, effectiveEventContext.workflowRepo ?? context.repo);
const workflowSource = process.env.GH_AW_WORKFLOW_SOURCE ?? "";
const workflowSourceURL = process.env.GH_AW_WORKFLOW_SOURCE_URL ?? "";

// Compute caution first so prefix assembly preserves the original execution order.
const detectionCaution = assembleMarkdownBodyParts({
includeFooter: false,
workflowName,
runUrl,
}).detectionCaution;

// Inject body header and disclosure header if configured (placed after caution, before user content)
const bodyHeader = getBodyHeader({ workflowName, runUrl });
const disclosureHeader = getDisclosureHeader({ workflowName, runUrl });

// Build prefix: caution (if any) → disclosure header (if any) → body header (if any) → user content
const prefixParts = [detectionCaution, disclosureHeader, bodyHeader].filter(Boolean);
const bodyPrefix = prefixParts.length > 0 ? prefixParts.join("\n\n") + "\n\n" : "";
let bodySuffix = "";

// Add tracker ID and footer
const trackerIDComment = getTrackerID("markdown");
if (trackerIDComment) {
bodySuffix += "\n\n" + trackerIDComment;
}

// Get triggering context for footer
const triggeringIssueNumber = context.payload.issue?.number;
const triggeringPRNumber = context.payload.pull_request?.number;
const triggeringDiscussionNumber = context.payload.discussion?.number;

// Generate history URL with type= based on execution context
const historyUrl =
generateHistoryUrl({
owner: repoParts.owner,
repo: repoParts.repo,
itemType: isDiscussion ? "discussion_comment" : "comment",
workflowCallId: callerWorkflowId,
workflowId,
serverUrl: context.serverUrl,
}) || undefined;

const markdownParts = assembleMarkdownBodyParts({
includeFooter,
workflowName,
const bodyNodes = parseReportMarkdown(stripExecutionProvenance(linkBody, { stripGroupingMarkers: true }), { minimumHeadingLevel: 2, allowMetadata: false, agentTainted: true, allowedMentions: allowedMentionAliases });
const report = buildIssueBodyReport("Comment", [...(message[COMMENT_PREAMBLE] || []), ...bodyNodes], {
repo: repoParts,
footer: includeFooter,
bodyFooter: config.body_footer,
allowedMentions: allowedMentionAliases,
itemType: isDiscussion ? "discussion_comment" : "comment",
runUrl,
workflowSource,
workflowSourceURL,
triggeringIssueNumber,
triggeringPRNumber,
triggeringDiscussionNumber,
historyUrl,
markerWhenFooterDisabled: "xml",
workflowIdMarker: false,
});

if (includeFooter) {
// When footer is enabled, add full footer with attribution and XML markers.
bodySuffix += "\n\n" + markdownParts.footer;
} else {
// When footer is disabled, only add XML marker for searchability (no visible attribution text)
bodySuffix += "\n\n" + markdownParts.noFooterMarker;
}
const bodyFooter = getBodyFooterMessage(config.body_footer, { workflowName, runUrl });
if (bodyFooter) {
bodySuffix += "\n\n" + bodyFooter.trimEnd();
}

// Add workflow-call-id marker when available to allow close-older-comments to
// distinguish callers that share the same reusable workflow (and GH_AW_WORKFLOW_ID)
if (callerWorkflowId) {
bodySuffix += "\n" + generateWorkflowCallIdMarker(callerWorkflowId);
}

const framedBody = bodyPrefix + linkBody + bodySuffix;
processedBody = appendExecutionProvenance(framedBody, workflowName, runUrl);
// Enforce max limits again after adding footer and metadata
// Length and mention limits include metadata; only agent content counts toward the link limit.
try {
if (processedBody.length > MAX_COMMENT_LENGTH) {
// Provenance replaces reserved markers; reserve its actual net overhead, not duplicate markers.
const fittingLimit = MAX_COMMENT_LENGTH + framedBody.length - processedBody.length;
if (fittingLimit < 1) throw new Error(`E006: Protected execution metadata exceeds the maximum body length of ${MAX_COMMENT_LENGTH} characters`);
processedBody = fitMarkdownBody(linkBody, { prefix: bodyPrefix, suffix: bodySuffix, maxLength: fittingLimit, allowedMentions: allowedMentionAliases });
processedBody = appendExecutionProvenance(processedBody, workflowName, runUrl);
}
processedBody = renderSizedReport(report, MAX_COMMENT_LENGTH).body;
enforceCommentLimits(processedBody, { maxLinks, linkBody });
} catch (error) {
const errorMessage = getErrorMessage(error);
Expand Down
Loading
Loading