diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 07f44381..a96ab5f3 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -64,6 +64,11 @@ scope, non-goals, and criteria; it does not authorize an automated implementatio run, a larger budget, or merging. Follow the documented rollout status before using it. Keep advisory replies conversational and assessment metadata in Actions; only an explicitly approved acceptance record publishes its proposed terms. +Completion receipts are fixed operational messages from trusted workflow code, +not model replies or approvals. Only canonical, same-target receipts from the +verified Actions bot may be excluded from discussion evidence; do not ignore +real replies, accepted scope records, or member comments. Preserve duplicate-write +and stale-context safeguards when changing these messages. Do not manufacture owner commands, edit sealed artifacts, or bypass stale-context, scan, or uncertain-publication checks. diff --git a/.github/workflows/discussion-draft.lock.yml b/.github/workflows/discussion-draft.lock.yml index 55984a66..8a0c594a 100644 --- a/.github/workflows/discussion-draft.lock.yml +++ b/.github/workflows/discussion-draft.lock.yml @@ -1,4 +1,4 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"866df3fe34ad1e3538ad16bf2206f4474354d0c43b29a432c51c13cc07293363","body_hash":"b22194887ef34c0f4f479f05cb741c0a7f0f651a159844fff12931f35670ce69","compiler_version":"v0.93.5","strict":true,"agent_id":"copilot","agent_model":"gpt-6.1-sol","engine_versions":{"copilot":"1.0.101"}} +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"503f09a806c9d75d1de37a91b27a228b832aa2913922e8ab63dd6d41fb1b3d5d","body_hash":"b22194887ef34c0f4f479f05cb741c0a7f0f651a159844fff12931f35670ce69","compiler_version":"v0.93.5","strict":true,"agent_id":"copilot","agent_model":"gpt-6.1-sol","engine_versions":{"copilot":"1.0.101"}} # gh-aw-manifest: {"version":1,"secrets":["GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/checkout","sha":"d23441a48e516b6c34aea4fa41551a30e30af803","version":"d23441a48e516b6c34aea4fa41551a30e30af803"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"9000827ccba6bdab643e8b6fd33ac0654aef8333"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"3a2844b7e9c422d3c10d287c895573f7108da1b3"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"cf430e030ddbb5b0abf93d22962f4752f3646cd9"},{"repo":"github/gh-aw/actions/setup","sha":"32ecafbc061c9af57e9361942099e381102ae304","version":"32ecafbc061c9af57e9361942099e381102ae304"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.28.70","digest":"sha256:b15ab48cbbab02904eb9bbd359a398db59690eebbea1e6934d47ed2bb407dd34","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.28.70@sha256:b15ab48cbbab02904eb9bbd359a398db59690eebbea1e6934d47ed2bb407dd34"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.70","digest":"sha256:9ac8f9c7294e892c916de3da9d2588dfd8cd4931e5c39b00143266d7ed9fd52a","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.70@sha256:9ac8f9c7294e892c916de3da9d2588dfd8cd4931e5c39b00143266d7ed9fd52a"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.28.70","digest":"sha256:b5bc53f4becfd96e926e63c83831f1b3c9512f713c83161d2b8c9b7204b3e917","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.28.70@sha256:b5bc53f4becfd96e926e63c83831f1b3c9512f713c83161d2b8c9b7204b3e917"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.37","digest":"sha256:9c7f242f6dec2d7d7b55d4c9e07872d59b85377c6cb3de46c915a5d1ffb91442","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.37@sha256:9c7f242f6dec2d7d7b55d4c9e07872d59b85377c6cb3de46c915a5d1ffb91442"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:23746305eeded20dc2726ab18bb081962d66ee3b2e09a54291afd1869ab3ef6d","pinned_image":"ghcr.io/github/gh-aw-node@sha256:23746305eeded20dc2726ab18bb081962d66ee3b2e09a54291afd1869ab3ef6d"},{"image":"ghcr.io/github/github-mcp-server:v2.0.3","digest":"sha256:250bc6ce70788207608ef74cef4397230ff2e8481218da74d6093e4bd9101132","pinned_image":"ghcr.io/github/github-mcp-server:v2.0.3@sha256:250bc6ce70788207608ef74cef4397230ff2e8481218da74d6093e4bd9101132"}],"mcp_servers":[{"name":"github","tools":["get_discussion","get_discussion_comments","get_file_contents","issue_read","list_issues","list_pull_requests","pull_request_read","search_issues","search_pull_requests"]},{"name":"safeoutputs","tools":["noop","report_incomplete","report_missing_data"]}],"threat_detection":{"mode":"enabled"},"admission":false} # This file was automatically generated by gh-aw (v0.93.5). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # @@ -70,7 +70,7 @@ concurrency: format('typechat-discussion-{0}-{1}-{2}', github.repository_id, github.event_name, github.event.issue.number || github.event.discussion.number) || format('typechat-ignored-draft-{0}', github.run_id) }} -run-name: TypeChat discussion response +run-name: "TypeChat response: ${{ github.event_name }} #${{ github.event.issue.number || github.event.discussion.number }} / comment ${{ github.event.comment.id }}" env: OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.GH_AW_DEFAULT_OTLP_ENDPOINT || vars.GH_AW_DEFAULT_OTLP_ENDPOINT }} diff --git a/.github/workflows/discussion-draft.md b/.github/workflows/discussion-draft.md index 65562508..65f5967c 100644 --- a/.github/workflows/discussion-draft.md +++ b/.github/workflows/discussion-draft.md @@ -1,7 +1,7 @@ --- name: TypeChat discussion response description: Prepare checked discussion responses and work proposals for separate owner approval. -run-name: "TypeChat discussion response" +run-name: "TypeChat response: ${{ github.event_name }} #${{ github.event.issue.number || github.event.discussion.number }} / comment ${{ github.event.comment.id }}" on: issue_comment: types: [created] diff --git a/.github/workflows/discussion-status.yml b/.github/workflows/discussion-status.yml new file mode 100644 index 00000000..b7d91308 --- /dev/null +++ b/.github/workflows/discussion-status.yml @@ -0,0 +1,174 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +name: Report TypeChat discussion outcome +run-name: Report TypeChat discussion outcome + +on: + workflow_run: + workflows: ["TypeChat discussion response"] + types: [completed] + +permissions: {} + +concurrency: + group: >- + ${{ github.repository == 'microsoft/TypeChat' && + github.event.workflow_run.actor.type == 'User' && + github.event.workflow_run.actor.id == 25374553 && + github.event.workflow_run.head_branch == github.event.repository.default_branch && + (github.event.workflow_run.event == 'issue_comment' || github.event.workflow_run.event == 'discussion_comment') && + (github.run_attempt == 1 || github.triggering_actor == 'robgruen') && + startsWith(github.event.workflow_run.display_title, 'TypeChat response: ') && + format('typechat-status-{0}-{1}', github.repository_id, github.event.workflow_run.display_title) || + format('typechat-ignored-status-{0}', github.run_id) }} + cancel-in-progress: false + +jobs: + issue_status: + name: Report the requested issue outcome + if: >- + github.repository == 'microsoft/TypeChat' && + github.event.workflow_run.actor.type == 'User' && + github.event.workflow_run.actor.id == 25374553 && + github.event.workflow_run.event == 'issue_comment' && + github.event.workflow_run.head_branch == github.event.repository.default_branch && + (github.run_attempt == 1 || github.triggering_actor == 'robgruen') + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + actions: read + pull-requests: read + issues: write + env: + TYPECHAT_STATUS_KIND: issue + steps: &status_steps + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Authenticate the completed run and original owner request + id: identify + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ github.token }} + retries: 0 + script: | + const path = require("node:path"); + const { pathToFileURL } = require("node:url"); + const helper = await import(pathToFileURL(path.join(process.env.GITHUB_WORKSPACE, "tools", "discussion-draft.mjs")).href); + const status = await helper.identifyStatus(github, context, process.env); + core.setOutput("eligible", status.eligible ? "true" : "false"); + if (!status.eligible) { + core.notice(status.reason); + await core.summary.addHeading("No completion comment needed").addRaw(status.reason).write(); + return; + } + core.setOutput("source_run_id", String(status.run.id)); + core.setOutput("artifact_id", status.artifact ? String(status.artifact.id) : ""); + - name: Download the completed draft for outcome verification + if: success() && steps.identify.outputs.eligible == 'true' && steps.identify.outputs.artifact_id != '' + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + artifact-ids: ${{ steps.identify.outputs.artifact_id }} + run-id: ${{ steps.identify.outputs.source_run_id }} + repository: ${{ github.repository }} + github-token: ${{ github.token }} + merge-multiple: true + path: ${{ runner.temp }}/typechat-status-draft + - name: Check the fixed receipt and previous write attempts + if: success() && steps.identify.outputs.eligible == 'true' + id: check + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + TYPECHAT_HAS_STATUS_DRAFT: ${{ steps.identify.outputs.artifact_id != '' }} + with: + github-token: ${{ github.token }} + retries: 0 + script: | + const path = require("node:path"); + const { pathToFileURL } = require("node:url"); + const helper = await import(pathToFileURL(path.join(process.env.GITHUB_WORKSPACE, "tools", "discussion-draft.mjs")).href); + const bundle = process.env.TYPECHAT_HAS_STATUS_DRAFT === "true" ? + helper.readJson(path.join(process.env.RUNNER_TEMP, "typechat-status-draft"), "sealed-draft.json", helper.MAX_BUNDLE_BYTES) : undefined; + const result = await helper.checkStatus(github, context, process.env, bundle); + core.setOutput("should_write", result.shouldWrite ? "true" : "false"); + if (!result.shouldWrite) { + core.notice(result.reason); + core.summary.addHeading("Completion already reported or no longer authorized").addRaw(result.reason); + if (result.url) core.summary.addLink("Existing result", result.url); + await core.summary.write(); + return; + } + const directory = path.join(process.env.RUNNER_TEMP, "typechat-status-intent"); + helper.writeJson(directory, "intent.json", result.intent); + core.setOutput("intent_name", result.intentName); + core.setOutput("intent_path", path.join(directory, "intent.json")); + - name: Preserve the status-write intent before any comment mutation + if: success() && steps.check.outputs.should_write == 'true' + id: intent + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ${{ steps.check.outputs.intent_name }} + path: ${{ steps.check.outputs.intent_path }} + if-no-files-found: error + overwrite: false + retention-days: 30 + - name: Revalidate and post or update the completion receipt + if: success() && steps.check.outputs.should_write == 'true' + id: publish + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + TYPECHAT_HAS_STATUS_DRAFT: ${{ steps.identify.outputs.artifact_id != '' }} + TYPECHAT_STATUS_INTENT_ID: ${{ steps.intent.outputs.artifact-id }} + with: + github-token: ${{ github.token }} + retries: 0 + script: | + const path = require("node:path"); + const { pathToFileURL } = require("node:url"); + const helper = await import(pathToFileURL(path.join(process.env.GITHUB_WORKSPACE, "tools", "discussion-draft.mjs")).href); + const bundle = process.env.TYPECHAT_HAS_STATUS_DRAFT === "true" ? + helper.readJson(path.join(process.env.RUNNER_TEMP, "typechat-status-draft"), "sealed-draft.json", helper.MAX_BUNDLE_BYTES) : undefined; + const result = await helper.publishStatus(github, context, process.env, bundle, Number(process.env.TYPECHAT_STATUS_INTENT_ID)); + const directory = path.join(process.env.RUNNER_TEMP, "typechat-status-result"); + helper.writeJson(directory, "result.json", { + ...result, sourceRunId: context.payload.workflow_run.id, sourceAttempt: context.payload.workflow_run.run_attempt, + }); + core.setOutput("result_path", path.join(directory, "result.json")); + core.summary.addHeading(result.posted ? "Completion receipt recorded" : "No new completion comment"); + if (result.url) core.summary.addLink("Result", result.url); + if (result.reason) core.summary.addRaw(result.reason); + await core.summary.write(); + if (result.outcome === "unavailable") { + core.setFailed("The source run had no available verified draft; the receipt requests maintainer inspection."); + } + - name: Preserve the completion result + if: always() && steps.publish.outputs.result_path != '' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: typechat-status-result-${{ github.run_attempt }} + path: ${{ steps.publish.outputs.result_path }} + if-no-files-found: error + overwrite: false + retention-days: 30 + discussion_status: + name: Report the requested Discussion outcome + if: >- + github.repository == 'microsoft/TypeChat' && + github.event.workflow_run.actor.type == 'User' && + github.event.workflow_run.actor.id == 25374553 && + github.event.workflow_run.event == 'discussion_comment' && + github.event.workflow_run.head_branch == github.event.repository.default_branch && + (github.run_attempt == 1 || github.triggering_actor == 'robgruen') + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + actions: read + pull-requests: read + discussions: write + env: + TYPECHAT_STATUS_KIND: discussion + steps: *status_steps diff --git a/AUTOMATION.md b/AUTOMATION.md index 5ab32dcd..d82ccce9 100644 --- a/AUTOMATION.md +++ b/AUTOMATION.md @@ -20,7 +20,7 @@ is available today. ## Status and implementation history -**Last updated: 2026-10-31 (UTC).** The read-only +**Last updated: 2026-11-01 (UTC).** The read-only [Backlog assessment workflow](https://github.com/microsoft/TypeChat/actions/workflows/backlog-assessment.lock.yml) is available for manual dispatch on `main`. The [latest run](https://github.com/microsoft/TypeChat/actions/runs/40997369231) @@ -38,9 +38,10 @@ reviews are now enabled through a separate repository rule; broader autonomy is not enabled. The [owner-approved discussion pilot](#second-pilot-owner-approved-discussion-drafts) has verified Issue draft-only, direct-reply, and duplicate-free reply retry runs. -Manual publication and the Discussion path remain unverified live. -[Exact owner work acceptance](#exact-work-acceptance) is prepared for review, -not activated or live-verified. +Manual response publication and the Discussion path remain unverified live. +[Exact owner work acceptance](#exact-work-acceptance) and its no-op retry are +live-verified on an Issue. [Completion receipts](#completion-receipts) are +prepared for review, not activated or live-verified. | Implemented | Change | Current state | | --- | --- | --- | @@ -66,7 +67,8 @@ not activated or live-verified. | Not enabled | Stricter human-review enforcement | Existing branch-review protections are retained at the owner's request. The written owner-approval requirement still applies. | | 2026-10-30 | [Owner-approved issue and Discussion drafts](#second-pilot-owner-approved-discussion-drafts) | Merged through [#493](https://github.com/microsoft/TypeChat/pull/493), [#494](https://github.com/microsoft/TypeChat/pull/494), and [#495](https://github.com/microsoft/TypeChat/pull/495). The Issue draft-only path passed in [run 41147057482](https://github.com/microsoft/TypeChat/actions/runs/41147057482) on 2026-10-31 (UTC); this does not verify publication or the Discussion path. | | 2026-10-31 | Conversational responses and `/typechat reply` | Merged through [#498](https://github.com/microsoft/TypeChat/pull/498). [Run 41226698016, attempt 1](https://github.com/microsoft/TypeChat/actions/runs/41226698016/attempts/1) posted one checked Issue response. [Attempt 2](https://github.com/microsoft/TypeChat/actions/runs/41226698016/attempts/2) skipped inference and posting, preserving the original reply. Discussion and manual publication remain unverified live. | -| 2026-10-31 | [Exact owner work acceptance](#exact-work-acceptance) | Prepared for review. `/typechat accept` approves an exact proposal, not an implementation run or merge. Activation and live verification are pending. | +| 2026-10-31 | [Exact owner work acceptance](#exact-work-acceptance) | Merged through [#503](https://github.com/microsoft/TypeChat/pull/503). [Run 41339605658, attempt 1](https://github.com/microsoft/TypeChat/actions/runs/41339605658/attempts/1) posted the exact Issue acceptance on 2026-11-01 (UTC); [attempt 2](https://github.com/microsoft/TypeChat/actions/runs/41339605658/attempts/2) skipped the write and preserved the original record. Discussion acceptance remains unverified live. | +| Prepared | [Completion receipts](#completion-receipts) | Close the loop for eyes-acknowledged draft/reply requests without publishing private previews or granting acceptance. Review, merge, and live verification are pending. | | Not yet | Human-approved agent implementation | Planned with a future 1,000-credit implementation allowance; no build command, implementation workflow, or implementation spending is enabled. | | Not yet | Selective automatic adoption | Future work, after public criteria and maintainer approval. | @@ -82,9 +84,9 @@ The agent-assisted workflow requires human authorization for public responses. `/typechat draft` and `/typechat publish` retain exact-text review. The owner-only `/typechat reply` command instead gives advance authorization for one advisory response after validation and threat detection; it does not authorize continuing -autonomous conversation. The acceptance extension adds a separate owner-only -`/typechat accept` command for exact proposed terms. It must not be used before -review and merge. Dispositions, acceptance of work, implementation runs, merging, +autonomous conversation. The separate owner-only `/typechat accept` command +approves exact proposed terms; its Issue path is live-verified. Dispositions, +acceptance of work, implementation runs, merging, and releases remain separate human decisions. Agents may investigate problems, summarize discussions, suggest questions, write @@ -487,9 +489,10 @@ human-review enforcement remain a separate owner decision. **Issue direct replies and no-op retries verified on 2026-10-31 (UTC).** This pilot provides GitHub-native previews and owner-requested replies for Issues -and Discussions; the Discussion and manual-publication paths still need live -verification. The exact work-acceptance extension is prepared for review and -must be merged and separately verified before rollout. No command changes labels, +and Discussions; the Discussion and manual response-publication paths still need +live verification. Issue work acceptance and its no-op retry were verified on +2026-11-01 (UTC). Completion receipts are prepared for review and need a separate +post-merge live check. No command changes labels, closes threads, starts an implementation run, creates PRs, or merges changes. Existing Copilot PR review remains a separate capability. @@ -500,10 +503,10 @@ command in a **new comment**, with no additional text: | Command | Authorization and result | | --- | --- | -| `/typechat draft` | Prepare a conversational reply for review and, when ready, a separate work-acceptance preview; do not post either. | +| `/typechat draft` | Prepare a conversational reply and, when ready, a work-acceptance preview; do not post either. After receipt rollout, report the operational outcome separately. | | `/typechat publish :` | Approve and post that exact reviewed draft. | | `/typechat reply` | Authorize one checked advisory reply to be posted without a second approval command. | -| `/typechat accept :` | After the acceptance extension is merged, approve and record the exact proposed scope and criteria. No implementation run or merge is authorized. | +| `/typechat accept :` | Approve and record the exact proposed scope and criteria. No implementation run or merge is authorized. | Use `/typechat draft` when you want to review the wording first. Use `/typechat reply` only when you want the agent to respond publicly after the @@ -554,9 +557,61 @@ Readiness classifications and suggested criteria are proposals only; a maintainer must still record a separate acceptance decision before development. Unclear scope or an item under consideration requires an owner decision. +### Completion receipts + +**Prepared for review; not live-verified.** Eyes acknowledge that a draft or +reply request has started. The separate +[outcome workflow](./.github/workflows/discussion-status.yml) waits for the full +response workflow to finish, including failures and cancellations, then records +one short, trusted operational outcome for the original command. + +The receipt links the owner request and run/preview. Its fixed messages distinguish +a prepared proposal, additional input, outdated or unavailable evidence, rejected +syntax, failure/cancellation, and an unconfirmed reply. It does not publish the +model's draft, questions, assessment, or private diagnostic text. Preparing a +draft is not accepting work or starting implementation. + +A successful public reply already serves as completion, so no extra "done" +comment is created. If a failure receipt already exists and a reply is later +confirmed, the same receipt is updated to link it. Manual response publication +and acceptance keep their existing outcome comments; this extension does not +add notifications to those separate publisher runs. + +Only the verified Actions bot's exact, canonical operational receipts are omitted +from frozen discussion evidence. Other bots, copied receipts on another target, +edited receipt text, substantive replies, acceptance records, and member responses +remain evidence. Thus a receipt does not itself make its draft stale, while real +discussion changes still do. + +The source run name carries trusted event, target, and comment identifiers, not +issue titles or comment prose. The completion workflow authenticates its own +default-branch code, the source workflow/run/repository/owner, and the unchanged +original command before any write. Issue and Discussion jobs have only their +own target's comment-write permission. No model or App credential is used. + +Receipts are serialized per command and guarded by durable create/update intents. +An identical outcome is a no-op; a newer outcome updates the managed comment, +not another comment. Update intents bind the exact receipt body being replaced, +not the source run or attempt. A later completion cannot mutate that same body +while an earlier update is unresolved. Observing the earlier canonical update +confirms it has taken effect before another mutation can proceed. +Edited receipts are not overwritten. A retained creation intent blocks +recreation after deletion. Both creation and updates require a command younger +than seven days, so their 30-day intents outlive the write-authorization window. +Intents and result artifacts are kept for 30 days. +Do not delete intents to force a retry after an uncertain API outcome. + +Delivery is fail-closed, not a guarantee of commenting despite lost permissions +or unavailable evidence. Withdrawn/edited requests, closed/locked targets, older +run-name formats, and superseded attempts do not receive new comments. If the +controller cannot authenticate or verify its inputs, Actions remains the error +channel. Use a new owner command after rollout; rerunning old workflow revisions +does not add the new request binding or receipt behavior. + ### Exact work acceptance -**Prepared for review; activation and live verification are pending.** Ordinary +**Issue acceptance and retry verified on 2026-11-01 (UTC); Discussion verification +is pending.** Ordinary human maintainer acceptance remains available. The automated pilot accepts only an explicit command from the project owner; it does not replace the normal maintainer process or grant the model acceptance authority. @@ -601,6 +656,14 @@ not edit a sealed artifact or silently rewrite an acceptance record. Removing an approval command does not erase an already posted decision. No implementation workflow consumes these records automatically. +The owner accepted [#504](https://github.com/microsoft/TypeChat/issues/504) using +the exact preview from [run 41337633188](https://github.com/microsoft/TypeChat/actions/runs/41337633188). +The [accepted record](https://github.com/microsoft/TypeChat/issues/504#issuecomment-6562465109) +matched the reviewed body hash, approval, producer, and durable intent. +[Publisher attempt 2](https://github.com/microsoft/TypeChat/actions/runs/41339605658/attempts/2) +skipped intent upload and posting; the record's text and timestamp were unchanged. +No coding agent, new permission, or implementation allowance was activated. + ### Drafting and posting are separate The [drafting source](./.github/workflows/discussion-draft.md) uses a trusted @@ -609,8 +672,11 @@ agent examines that snapshot and related contributions. It writes the actual reply and a separate assessment containing questions, recorded requirements, suggested criteria, a readiness recommendation, and an eligible proposal or explicit `null`. The model never marks its own proposal accepted. -Thread context is bounded at 1 MiB and 1,000 comments, including replies; -incomplete or oversized context is an error, not silent truncation. +Discussion evidence remains bounded at 1 MiB and 1,000 non-receipt comments, +including replies. Canonical operational receipts have a separate collection +allowance so they do not consume that existing budget: the raw thread is capped +at 2 MiB and 2,000 comments. The prepared model context still has its original +1 MiB limit. Incomplete or oversized context is an error, not silent truncation. Do not seed a native `noop` before model execution: the pinned runtime interprets it as completed work and skips the model. The model writes the candidate first, @@ -761,20 +827,29 @@ one. Wait for each operation to finish during the pilot. ### First live verification -The Issue `/typechat reply` and no-op retry checks passed in the runs recorded -above. Manual publication and Discussions still need separate live checks: +The Issue `/typechat reply` and `/typechat accept` paths and their no-op retries +passed in the runs recorded above. Manual response publication and Discussions +still need separate live checks: request `/typechat draft`, review its preview, approve its exact publish command, and verify a no-op publication retry. Exercise the Discussion path separately rather than inferring its permissions from an Issue run. -After review and merge of acceptance support, choose genuinely agreed, in-scope -work for a fresh draft. An accept command is a real human acceptance decision, +For additional acceptance checks, choose genuinely agreed, in-scope work for a +fresh draft. An accept command is a real human acceptance decision, not a harmless test: do not approve unresolved work merely to exercise the workflow. Review the exact acceptance preview, approve it, verify one unchanged record on retry, and check both Issue and Discussion writers separately. Use new commands to test new code, not reruns of older workflow revisions. -Record the confirming runs before marking this capability active. Local tests +After completion receipts are reviewed and merged, verify a new owner draft +receives exactly one fixed outcome comment with the correct run link. Confirm +that the receipt does not stale the draft before exact publication/acceptance, +that a repeated completion does not duplicate it, and that failures/cancellations +are distinguished from a prepared proposal. Verify the Discussion path separately. +Do not manufacture owner commands or malformed model output just to force a +successful result; use genuine owner-authorized cases and preserve blocked states. + +Record the confirming runs before marking a new path active. Local tests and compilation do not prove live Actions-token permissions or model access. ## From discussion to a reviewed change diff --git a/OWNER-CHEATSHEET.md b/OWNER-CHEATSHEET.md index 2b64d7a5..52196b47 100644 --- a/OWNER-CHEATSHEET.md +++ b/OWNER-CHEATSHEET.md @@ -1,6 +1,6 @@ # TypeChat owner cheat sheet -**For @robgruen. Last checked: 2026-10-31 (UTC).** +**For @robgruen. Last checked: 2026-11-01 (UTC).** [Issues](https://github.com/microsoft/TypeChat/issues) | [Discussions](https://github.com/microsoft/TypeChat/discussions) | @@ -10,8 +10,9 @@ [Full automation guide](./AUTOMATION.md) **Verified:** backlog assessment, automatic Copilot PR reviews, Issue draft generation, -and Issue `/typechat reply` delivery with a duplicate-free rerun. -**Awaiting review and live verification:** exact-proposal `/typechat accept`. +Issue `/typechat reply` delivery, and exact Issue `/typechat accept`, including +duplicate-free reruns. +**Awaiting review and live verification:** completion receipts for draft/reply requests. Manual publication and the Discussion path still need live verification. **Still human decisions:** work acceptance, implementation handoff, merging, and releases. @@ -23,7 +24,7 @@ Manual publication and the Discussion path still need live verification. | Have the agent answer an issue or Discussion | [Request one direct reply](#reply-directly); the Issue path is live-verified. | One checked conversational response, without accepting work. | | Review wording before responding | [Request a draft](#draft-and-publish). | The actual reply as a preview; assessment metadata stays in Actions. | | Post the proposed response | Review the exact draft, then copy its publish command into the same thread. | One Actions-bot comment, not approval to build. | -| Accept an agent-prepared proposal | After acceptance rollout, [review and approve its exact terms](#accept-an-exact-proposal). Until then, [record a human decision manually](#accept-work-manually). | A visible scope agreement; no coding agent starts automatically. | +| Accept an agent-prepared proposal | [Review and approve its exact terms](#accept-an-exact-proposal), or [record a human decision manually](#accept-work-manually). The Issue path is live-verified. | A visible scope agreement; no coding agent starts automatically. | | Move an existing PR forward | [Review the latest revision](#review-and-merge-manually); support the existing contributor rather than duplicate their PR. | A human decision to request changes or merge. | | Resolve unclear or out-of-scope work | Pause dependent work. If changing direction, approve and merge a [policy PR](./GOALS.md#who-decides) first. | An explicit scope decision; popularity or a label is not approval. | @@ -82,6 +83,11 @@ The Actions bot acknowledges the command comment with an `eyes` reaction when the workflow starts processing it. This is not a success or acceptance signal; check Actions for progress and errors. +After completion-receipt rollout, a short status comment will link the run and +say whether the draft is prepared, needs input, is outdated, or failed. The +receipt is not the drafted response and is not acceptance. It is safe to review +the original frozen preview after a canonical receipt appears. + **2. Review:** Open **Actions > TypeChat discussion response**, wait for the run to succeed, and open the **Seal discussion draft** job summary. It contains the exact public reply, the approval command, and a separate assessment that is not @@ -106,8 +112,8 @@ operation to finish before sending another command on that thread. ## Accept an exact proposal -**Prepared for review; do not use until merged and ready for owner-commanded -live verification.** This is a real scope decision, not a test acknowledgment. +**The Issue path and no-op retry are live-verified; Discussions still need a +separate check.** This is a real scope decision, not a test acknowledgment. 1. Resolve open questions, check the approved policy and existing contributions, then request a new `/typechat draft` on the same thread. @@ -149,8 +155,8 @@ This is not approval to merge. Material scope changes return to discussion. ``` This remains an ordinary human comment, not an automation command. It does not -assign a coding agent. The separate exact-proposal acceptance command is pending -rollout; **no `/typechat build` command or implementation workflow is enabled**. +assign a coding agent. Exact-proposal acceptance is also available on Issues; +**no `/typechat build` command or implementation workflow is enabled**. ## Review and merge manually @@ -174,6 +180,9 @@ rollout; **no `/typechat build` command or implementation workflow is enabled**. | Acceptance says "already accepted" | Follow the existing record. No second acceptance comment is needed. | | No acceptance preview or wrong acceptance hash | Resolve the questions or scope, then request and review a new draft. Do not substitute the response hash or edit artifacts. | | A reply command says "already answered" | Follow the existing reply link. No new model execution or comment is needed. | +| Eyes are present but no completion message appears | Receipt rollout must be merged and live-verified first. After rollout, check **Report TypeChat discussion outcome**. Existing public replies count as completion; removed/edited commands and closed/locked targets do not receive another comment. | +| A completion receipt reports an unconfirmed reply or uncertain write | Inspect the run and thread before retrying. A newer attempt cannot bypass an unresolved update to the same receipt. Do not delete the intent. Receipt mutations stop seven days after the original command; use a fresh request after inspection. | +| A receipt was edited or removed | Automation will not overwrite edited text or blindly recreate a missing receipt. Use the existing run evidence and inspect any retained intent before recovery. | | Workflow code changed | After merge and CI, use a new command. Old runs retain their original code, and older sealed artifacts may be stale. | | Publishing times out or reports an uncertain outcome | Inspect the thread and original run first. Do not retry blindly or delete the publication-intent artifact; resolve the uncertainty before approving a new draft. | | Assessment/drafting stops on a budget or evidence limit | Read the failure and coverage notes. Narrow the task or seek an owner-reviewed configuration change; do not bypass restrictions. | diff --git a/README.md b/README.md index 96e087a1..a9df47e9 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ proposals progress from discussion to accepted, reviewed changes with less manual coordination. Read about the [automation experiment](./AUTOMATION.md) and how to participate. -**Status as of 2026-10-31 (UTC):** The +**Status as of 2026-11-01 (UTC):** The [latest backlog assessment](https://github.com/microsoft/TypeChat/actions/runs/40997369231) completed successfully after the control hardening merged through [#491](https://github.com/microsoft/TypeChat/pull/491). It inventories 20 issues @@ -93,9 +93,10 @@ has verified Issue draft generation, conversational `/typechat reply` delivery, and a duplicate-free reply retry after [#498](https://github.com/microsoft/TypeChat/pull/498) merged. Manual publication and Discussions still need live verification. `/typechat draft` remains preview-only, with exact-text response approval through -`/typechat publish`. The next milestone prepares an explicit owner-only -`/typechat accept` for the exact proposed scope and criteria; review, merge, and -live verification are pending. Generation keeps its 50-credit main budget and +`/typechat publish`. Owner-only `/typechat accept` and its no-op retry have also +been verified on an Issue after [#503](https://github.com/microsoft/TypeChat/pull/503) +merged. Completion-only operational receipts are prepared for review; they do +not publish draft content or accept work. Generation keeps its 50-credit main budget and separately budgeted detection. Acceptance does not launch a coding agent or enable the future implementation budget. @@ -120,7 +121,8 @@ enable the future implementation budget. | Stricter human-review enforcement | Not enabled | Existing branch-review protections are retained at the owner's request. Copilot reviews do not replace human approval. | | Owner-approved issue and Discussion drafts | 2026-10-30 | Merged through [#495](https://github.com/microsoft/TypeChat/pull/495); [run 41147057482](https://github.com/microsoft/TypeChat/actions/runs/41147057482) verified the Issue draft-only path. Publication and Discussion-path verification remain separate. | | Owner-commanded direct replies | 2026-10-31 | Merged through [#498](https://github.com/microsoft/TypeChat/pull/498). [Attempt 1](https://github.com/microsoft/TypeChat/actions/runs/41226698016/attempts/1) posted one Issue reply; [attempt 2](https://github.com/microsoft/TypeChat/actions/runs/41226698016/attempts/2) skipped inference and posting, preserving the original comment. Other paths remain unverified live. | -| Exact owner work acceptance | 2026-10-31 | [Prepared for review](./AUTOMATION.md#exact-work-acceptance): approve the exact proposed scope, non-goals, and criteria with `/typechat accept`. No agent implementation or merge authorization; activation and live verification pending. | +| Exact owner work acceptance | 2026-10-31 | Merged through [#503](https://github.com/microsoft/TypeChat/pull/503). [Attempt 1](https://github.com/microsoft/TypeChat/actions/runs/41339605658/attempts/1) recorded the approved Issue scope; [attempt 2](https://github.com/microsoft/TypeChat/actions/runs/41339605658/attempts/2) preserved one unchanged record. No coding run or budget was activated; Discussion verification remains pending. | +| Completion receipts | Prepared | [Close the loop after eyes acknowledgment](./AUTOMATION.md#completion-receipts) without publishing model drafts or duplicating existing replies. Review, merge, and live verification pending. | | Agent implementation | Not yet | A separate human authorization and future 1,000-credit implementation allowance are documented, not enabled. | | Selective automatic adoption of community proposals | Not yet | Future work, subject to public criteria and maintainer approval. | diff --git a/tools/discussion-draft.mjs b/tools/discussion-draft.mjs index 45ee2342..37d5adb8 100644 --- a/tools/discussion-draft.mjs +++ b/tools/discussion-draft.mjs @@ -11,8 +11,10 @@ export const REPOSITORY = Object.freeze({ owner: "microsoft", repo: "TypeChat", export const ACTIONS_BOT_ID = "MDM6Qm90NDE4OTgyODI="; export const DRAFT_WORKFLOW = ".github/workflows/discussion-draft.lock.yml"; export const PUBLISH_WORKFLOW = ".github/workflows/publish-discussion-draft.yml"; +export const STATUS_WORKFLOW = ".github/workflows/discussion-status.yml"; export const DRAFT_ARTIFACT_PREFIX = "typechat-discussion-draft-"; export const INTENT_PREFIX = "typechat-publish-intent-"; +export const STATUS_INTENT_PREFIX = "typechat-status-intent-"; export const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; export const MAX_CONTEXT_BYTES = 1048576; export const MAX_DRAFT_BYTES = 65536; @@ -25,6 +27,7 @@ export const CONTROL_PATHS = Object.freeze([ ".github/workflows/discussion-draft.md", DRAFT_WORKFLOW, PUBLISH_WORKFLOW, + STATUS_WORKFLOW, ".github/workflows/shared/read-only-analysis.md", "tools/discussion-draft.mjs", ]); @@ -36,6 +39,7 @@ const SHA1 = /^[a-f0-9]{40}$/; const SHA256 = /^[a-f0-9]{64}$/; const SCOPES = ["in_scope", "needs_owner_decision", "conflicts_with_direction"]; const READINESS = ["needs_clarification", "ready_for_owner_decision", "existing_pr_review", "blocked_by_evidence", "needs_owner_scope_decision"]; +const STATUS_OUTCOMES = ["ready", "input", "outdated", "unavailable", "failed", "cancelled", "invalid", "unconfirmed", "replied"]; function requireValue(condition, message) { if (!condition) { @@ -126,9 +130,10 @@ export function parseCommand(body) { } function isControlComment(comment) { - return comment.author?.type === "User" && comment.author.login === OWNER.login && + return (comment.author?.type === "User" && comment.author.login === OWNER.login && (/^\/typechat (draft|reply)\s*$/.test(comment.body) || - /^\/typechat (publish|accept) [1-9][0-9]*:[a-fA-F0-9]{64}\s*$/.test(comment.body)); + /^\/typechat (publish|accept) [1-9][0-9]*:[a-fA-F0-9]{64}\s*$/.test(comment.body))) || + statusReceiptData(comment) !== null; } export function authorize(context, env, action) { @@ -255,10 +260,20 @@ export async function readThread(github, target) { const comments = []; const cursors = new Set(); let commentBytes = 0; + let evidenceBytes = 0; + let evidenceCount = 0; function appendComment(value, parentId) { const comment = normalizeComment(value, parentId); - commentBytes += Buffer.byteLength(JSON.stringify(comment)); - requireValue(comments.length < 1000 && commentBytes <= MAX_CONTEXT_BYTES, + const bytes = Buffer.byteLength(JSON.stringify(comment)); + commentBytes += bytes; + requireValue(comments.length < 2000 && commentBytes <= MAX_CONTEXT_BYTES * 2, + "This thread exceeds the bounded 2,000-comment receipt collection limit."); + if (!statusReceiptData(comment)) { + evidenceBytes += bytes; + evidenceCount++; + } + requireValue(evidenceCount <= 1000, "This thread exceeds the pilot's 1,000-comment limit."); + requireValue(evidenceBytes <= MAX_CONTEXT_BYTES, "This thread exceeds the pilot's bounded context limit."); comments.push(comment); } @@ -271,7 +286,7 @@ export async function readThread(github, target) { const page = connection(item.comments); requireValue(total === undefined || total === page.totalCount, "The discussion changed during pagination. Request a new draft."); total = page.totalCount; - requireValue(total <= 1000, "This thread exceeds the pilot's 1,000-comment limit."); + requireValue(total <= 2000, "This thread exceeds the bounded 2,000-comment receipt collection limit."); for (const node of page.nodes) { appendComment(node, null); topCount++; @@ -286,7 +301,7 @@ export async function readThread(github, target) { appendComment(reply, node.id); replyCount++; } - requireValue(comments.length <= 1000, "This thread exceeds the pilot's 1,000-comment limit."); + requireValue(comments.length <= 2000, "This thread exceeds the bounded 2,000-comment receipt collection limit."); if (!replyPage.pageInfo.hasNextPage) { break; } @@ -303,7 +318,7 @@ export async function readThread(github, target) { requireValue(replyCount === replyTotal, "Reply coverage is incomplete."); } } - requireValue(comments.length <= 1000, "This thread exceeds the pilot's 1,000-comment limit."); + requireValue(comments.length <= 2000, "This thread exceeds the bounded 2,000-comment receipt collection limit."); after = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null; if (after) { requireValue(!cursors.has(after), "Repeated comment cursor; context coverage is incomplete."); @@ -314,7 +329,9 @@ export async function readThread(github, target) { "Comment coverage is incomplete or duplicated."); comments.sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0); const thread = { target: core, comments }; - requireValue(Buffer.byteLength(JSON.stringify(thread)) <= MAX_CONTEXT_BYTES, "This context exceeds the pilot's 1 MiB limit."); + requireValue(Buffer.byteLength(JSON.stringify(thread)) <= MAX_CONTEXT_BYTES * 2, "This receipt collection exceeds its 2 MiB limit."); + requireValue(Buffer.byteLength(JSON.stringify({ target: core, comments: comments.filter(comment => !statusReceiptData(comment)) })) <= + MAX_CONTEXT_BYTES, "This context exceeds the pilot's 1 MiB limit."); return thread; } @@ -322,7 +339,7 @@ export function snapshotHash(thread) { return digest({ target: thread.target, comments: thread.comments.filter(comment => !isControlComment(comment)) }); } -export async function verifyCommand(github, request) { +async function verifyOwnerCommand(github, request) { const result = await github.graphql(`query DiscussionPilotCommand($id:ID!) { node(id:$id) { __typename @@ -351,6 +368,11 @@ export async function verifyCommand(github, request) { requireValue(lf(comment.body) === request.commandBody && Date.parse(comment.createdAt) === Date.parse(request.commandCreatedAt) && comment.lastEditedAt === null, "Edited or withdrawn commands cannot authorize work. Post a new command."); + return comment; +} + +export async function verifyCommand(github, request) { + const comment = await verifyOwnerCommand(github, request); requireValue(equal(parseCommand(comment.body), request.command), "The command changed after the event."); return comment; } @@ -639,13 +661,20 @@ function markerFor(bundle) { }); } -async function verifyReferences(github, references) { +async function changedReference(github, references) { for (const reference of references) { const pr = (await github.rest.pulls.get({ ...API_REPO, pull_number: reference.number })).data; - requireValue(pr.number === reference.number && pr.base?.repo?.id === REPOSITORY.id && - pr.head?.sha === reference.headSha && pr.updated_at === reference.updatedAt, - `PR #${reference.number} changed or its inspected revision is unverified. Request a new draft.`); + if (pr.number !== reference.number || pr.base?.repo?.id !== REPOSITORY.id || + pr.head?.sha !== reference.headSha || pr.updated_at !== reference.updatedAt) { + return reference.number; + } } + return null; +} + +async function verifyReferences(github, references) { + const changed = await changedReference(github, references); + requireValue(changed === null, `PR #${changed} changed or its inspected revision is unverified. Request a new draft.`); } export async function sealDraft(github, context, env, prepared, candidate, clock = () => new Date()) { @@ -808,37 +837,43 @@ export async function identifyPublication(github, context, env, clock = () => ne return { request, artifact, run, controls, validUntil, bodyHash }; } -function validateBundle(bundle, publication) { +function validateSealedDraft(bundle, evidence) { exactKeys(bundle, ["version", "target", "request", "producer", "fingerprints", "snapshotHash", "createdAt", "draft", "marker", "body", "bodyHash", "acceptance"], "Unexpected review-bundle fields."); - requireValue(bundle.version === 3 && equal(bundle.target, publication.request.target), "The draft belongs to another target or protocol version."); + requireValue(bundle.version === 3 && equal(bundle.target, evidence.request.target), "The draft belongs to another target or protocol version."); requireValue(equal(bundle.producer, { - runId: publication.run.id, attempt: publication.run.run_attempt, - commit: publication.run.head_sha, workflow: DRAFT_WORKFLOW, + runId: evidence.run.id, attempt: evidence.run.run_attempt, + commit: evidence.run.head_sha, workflow: DRAFT_WORKFLOW, }), "Producer provenance does not match the artifact."); requireValue(SHA256.test(bundle.snapshotHash) && SHA256.test(bundle.marker) && SHA256.test(bundle.bodyHash), "Missing draft integrity values."); timestamp(bundle.createdAt, "Missing draft creation time."); exactKeys(bundle.request, ["commentId", "commandBody", "commandCreatedAt"], "Missing original draft request."); identifier(bundle.request.commentId, "Missing original request ID."); - const directReply = publication.request.command.action === "reply"; - requireValue(parseCommand(bundle.request.commandBody).action === (directReply ? "reply" : "draft"), - "The source request does not authorize this publication mode."); - if (directReply) { - requireValue(equal(bundle.request, originalRequest(publication.request)), - "The sealed reply belongs to a different owner command."); - } + requireValue(["draft", "reply"].includes(parseCommand(bundle.request.commandBody).action), + "The source request is not a draft or reply command."); timestamp(bundle.request.commandCreatedAt, "Missing original request time."); const createdAt = Date.parse(bundle.createdAt); // GitHub artifact creation timestamps have only whole-second precision. requireValue(createdAt >= Date.parse(bundle.request.commandCreatedAt) && - Math.floor(createdAt / 1000) <= Math.floor(Date.parse(publication.artifact.created_at) / 1000), + Math.floor(createdAt / 1000) <= Math.floor(Date.parse(evidence.artifact.created_at) / 1000), "The draft's creation time does not match its recorded provenance."); requireValue(equal(validateDraft(bundle.draft), bundle.draft), "The draft does not match the supported schema."); - requireValue(equal(bundle.fingerprints, publication.controls.fingerprints), "Policy or workflow code changed. Request a new draft."); + requireValue(equal(bundle.fingerprints, evidence.controls.fingerprints), "Policy or workflow code changed. Request a new draft."); requireValue(markerFor(bundle) === bundle.marker && renderDraft(bundle) === bundle.body && digest(bundle.body) === bundle.bodyHash && equal(acceptanceFor(bundle), bundle.acceptance), "The sealed response or acceptance preview changed."); +} + +function validateBundle(bundle, publication) { + validateSealedDraft(bundle, publication); + const directReply = publication.request.command.action === "reply"; + requireValue(parseCommand(bundle.request.commandBody).action === (directReply ? "reply" : "draft"), + "The source request does not authorize this publication mode."); + if (directReply) { + requireValue(equal(bundle.request, originalRequest(publication.request)), + "The sealed reply belongs to a different owner command."); + } requireValue(publicationContent(bundle, publication.request.command.action).bodyHash === publication.bodyHash, "The approval does not match the exact rendered draft."); } @@ -954,27 +989,341 @@ export async function publishDraft(github, context, env, bundle, intentId, clock } await verifyCommand(github, latest.request); const content = publicationContent(bundle, latest.request.command.action); + const comment = await writeDiscussionComment(github, bundle.target, content.body); + return { posted: true, id: comment.id, url: comment.url, bodyHash: content.bodyHash }; +} + +async function writeDiscussionComment(github, target, body, existing = null) { + const commentId = existing && target.kind === "issue" ? + integer(Number(existing.url.split("#issuecomment-")[1]), "Invalid receipt comment URL.") : null; let comment; try { - if (bundle.target.kind === "issue") { - const result = await github.rest.issues.createComment({ - ...API_REPO, issue_number: bundle.target.number, body: content.body, - }); + if (target.kind === "issue") { + const result = existing ? + await github.rest.issues.updateComment({ + ...API_REPO, comment_id: commentId, body, + }) : + await github.rest.issues.createComment({ ...API_REPO, issue_number: target.number, body }); comment = { id: result.data.node_id, url: result.data.html_url, body: result.data.body }; + } else if (existing) { + const result = await github.graphql(`mutation DiscussionPilotUpdate($id:ID!,$body:String!) { + updateDiscussionComment(input:{commentId:$id,body:$body}) { comment { id url body } } + }`, { id: existing.id, body }); + comment = result.updateDiscussionComment?.comment; } else { const result = await github.graphql(`mutation DiscussionPilotPost($id:ID!,$body:String!) { addDiscussionComment(input:{discussionId:$id,body:$body}) { comment { id url body } } - }`, { id: bundle.target.id, body: content.body }); + }`, { id: target.id, body }); comment = result.addDiscussionComment?.comment; } } catch (error) { throw new Error("Publication outcome is uncertain. The intent is retained; inspect GitHub before any manual recovery.", { cause: error }); } requireValue(comment && typeof comment.id === "string" && typeof comment.url === "string" && - comment.url.startsWith(bundle.target.url + "#") && - typeof comment.body === "string" && lf(comment.body) === content.body, + comment.url.startsWith(target.url + "#") && typeof comment.body === "string" && lf(comment.body) === body && + (!existing || (comment.id === existing.id && comment.url === existing.url)), "GitHub did not confirm the exact comment. The intent is retained; inspect before retrying."); - return { posted: true, id: comment.id, url: comment.url, bodyHash: content.bodyHash }; + return comment; +} + +function statusKey(data) { + return digest({ kind: data.kind, number: data.number, commentId: data.commentId }); +} + +function validStatusData(data) { + return data !== null && typeof data === "object" && !Array.isArray(data) && + equal(Object.keys(data).sort(), ["version", "kind", "number", "commentId", "runId", "attempt", "started", + "action", "outcome", "result"].sort()) && + data.version === 1 && ["issue", "discussion"].includes(data.kind) && + ["number", "commentId", "runId", "attempt", "started"].every(key => Number.isSafeInteger(data[key]) && data[key] > 0) && + ["draft", "reply"].includes(data.action) && STATUS_OUTCOMES.includes(data.outcome) && + (["ready", "input", "outdated", "unavailable"].includes(data.outcome) ? data.action === "draft" : true) && + (["unconfirmed", "replied"].includes(data.outcome) ? data.action === "reply" : true) && + (data.outcome === "replied" ? typeof data.result === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(data.result) : data.result === ""); +} + +export function renderStatusReceipt(data) { + requireValue(validStatusData(data), "Invalid completion-receipt metadata."); + const targetUrl = `${REPO_URL}/${data.kind === "issue" ? "issues" : "discussions"}/${data.number}`; + const fragment = data.kind === "issue" ? "issuecomment" : "discussioncomment"; + const messages = { + ready: "Draft and work-acceptance preview prepared for owner review.", + input: "Draft prepared; owner or maintainer input is still needed before work acceptance.", + outdated: "The draft is no longer current. Review the thread and request a fresh draft.", + unavailable: "The run finished without an available, verified review artifact. Maintainer inspection is needed.", + failed: "The request failed. Check the run and thread before retrying.", + cancelled: "The request was cancelled or timed out. Check the run and thread before retrying.", + invalid: "The request was rejected. Post only /typechat draft or /typechat reply in a new comment.", + unconfirmed: "A reply was not confirmed. Inspect the run and thread before retrying; do not assume nothing was posted.", + replied: "The requested reply is available.", + }; + const sections = [ + `**TypeChat: ${messages[data.outcome]}**`, + `[Owner request](${targetUrl}#${fragment}-${data.commentId}) | ` + + `[Run${data.action === "draft" ? " and preview" : ""}](${REPO_URL}/actions/runs/${data.runId}/attempts/${data.attempt})`, + ]; + if (data.result) { + sections.push(`[Existing reply](${targetUrl}#${fragment}-${data.result})`); + } + sections.push("*Operational receipt only. This comment does not publish draft text, accept work, " + + "authorize implementation, or approve merging.*"); + sections.push(``); + return sections.join("\n\n") + "\n"; +} + +function statusReceiptData(comment) { + // A marker alone must never hide arbitrary discussion text from the snapshot. + if (comment.author?.type !== "Bot" || comment.author.id !== ACTIONS_BOT_ID || comment.parentId !== null || + typeof comment.body !== "string" || comment.body.length > MAX_COMMENT_BYTES) { + return null; + } + const match = /\n?$/.exec(lf(comment.body)); + if (!match) { + return null; + } + const data = { + version: 1, kind: match[2], number: Number(match[3]), commentId: Number(match[4]), + runId: Number(match[5]), attempt: Number(match[6]), started: Number(match[7]), + action: match[8], outcome: match[9], result: match[10], + }; + const targetUrl = `${REPO_URL}/${data.kind === "issue" ? "issues" : "discussions"}/${data.number}`; + return validStatusData(data) && match[1] === statusKey(data) && + comment.url?.startsWith(targetUrl + "#") && lf(comment.body) === renderStatusReceipt(data) ? data : null; +} + +export function parseStatusRunTitle(title) { + const match = /^TypeChat response: (issue_comment|discussion_comment) #([1-9][0-9]*) \/ comment ([1-9][0-9]*)$/.exec( + string(title, "Missing source run title.", 256)); + if (!match) { + requireValue(!title.startsWith("TypeChat response:"), "Malformed source owner-request binding."); + return null; + } + return { + kind: match[1] === "issue_comment" ? "issue" : "discussion", + number: integer(Number(match[2]), "Invalid receipt target number."), + commentId: integer(Number(match[3]), "Invalid receipt request ID."), + }; +} + +export async function identifyStatus(github, context, env, clock = () => new Date()) { + const event = object(context.payload, "Missing completion event."); + requireValue(context.eventName === "workflow_run" && event.action === "completed" && + event.repository?.id === REPOSITORY.id && event.repository.full_name === REPO_NAME && + event.repository.private === false, "Only completion events in the public target repository can authorize a receipt."); + const branch = identifier(event.repository.default_branch, "Missing default branch."); + requireValue(env.GITHUB_WORKFLOW_REF === `${REPO_NAME}/${STATUS_WORKFLOW}@refs/heads/${branch}` && + env.GITHUB_REF === `refs/heads/${branch}` && SHA1.test(context.sha), + "Completion receipts require trusted default-branch code."); + const attempt = integer(Number(env.GITHUB_RUN_ATTEMPT), "Invalid receipt workflow attempt."); + requireValue(attempt === 1 || env.GITHUB_TRIGGERING_ACTOR === OWNER.login, + "Only the owner can rerun a completion-receipt job."); + const runId = integer(event.workflow_run?.id, "Missing source workflow run."); + const sourceAttempt = integer(event.workflow_run?.run_attempt, "Missing source completion attempt."); + const run = (await github.rest.actions.getWorkflowRun({ ...API_REPO, run_id: runId })).data; + const workflow = (await github.rest.actions.getWorkflow({ ...API_REPO, workflow_id: path.posix.basename(DRAFT_WORKFLOW) })).data; + requireValue(run?.id === runId && run.workflow_id === workflow.id && + [DRAFT_WORKFLOW, `${DRAFT_WORKFLOW}@refs/heads/${branch}`].includes(run.path) && + run.repository?.id === REPOSITORY.id && run.head_repository?.id === REPOSITORY.id && + run.head_branch === branch && SHA1.test(run.head_sha) && + run.actor?.type === "User" && run.actor.id === OWNER.id && + run.triggering_actor?.type === "User" && run.triggering_actor.id === OWNER.id && + ["issue_comment", "discussion_comment"].includes(run.event), + "The source run is not an authorized owner request on the default branch."); + integer(run.run_attempt, "Missing source attempt."); + if (run.status !== "completed" || run.run_attempt !== sourceAttempt) { + return { eligible: false, reason: "A newer source attempt is pending or this completion event is stale." }; + } + const started = Date.parse(timestamp(run.run_started_at, "Missing source start time.")); + const created = Date.parse(timestamp(run.created_at, "Missing source creation time.")); + const now = clock().getTime(); + requireValue(created <= started && now >= started && now < started + MAX_AGE_MS, "The completion event is stale or has invalid timing."); + requireValue(["success", "failure", "cancelled", "timed_out", "action_required", "neutral", "skipped", "stale", "startup_failure"] + .includes(run.conclusion), "Missing or unsupported source conclusion."); + const locator = parseStatusRunTitle(run.display_title); + if (!locator || run.conclusion === "skipped") { + return { eligible: false, reason: "This ignored or older run has no supported owner-request binding." }; + } + requireValue(run.event === `${locator.kind}_comment` && env.TYPECHAT_STATUS_KIND === locator.kind, + "The receipt job does not have authority for this target kind."); + const controls = await currentControls(github); + const executing = await readControls(github, context.sha); + requireValue(equal(executing.fingerprints, controls.fingerprints), "Receipt code or policy changed while queued."); + const targetResult = await github.graphql(`query DiscussionStatusTarget($owner:String!,$repo:String!,$number:Int!) { + repository(owner:$owner,name:$repo) { + nameWithOwner isPrivate + target:${locator.kind === "issue" ? "issue" : "discussion"}(number:$number) { id number url } + } + }`, { ...API_REPO, number: locator.number }); + validateRepository(targetResult.repository); + const item = object(targetResult.repository.target, "The receipt target is unavailable."); + const target = { + kind: locator.kind, number: locator.number, id: identifier(item.id, "Missing receipt target ID."), + url: `${REPO_URL}/${locator.kind === "issue" ? "issues" : "discussions"}/${locator.number}`, + }; + requireValue(item.number === target.number && item.url === target.url, "Unexpected receipt target."); + const thread = await readThread(github, target); + const commandUrl = `${target.url}#${target.kind === "issue" ? "issuecomment" : "discussioncomment"}-${locator.commentId}`; + const matches = thread.comments.filter(comment => comment.url === commandUrl); + requireValue(matches.length <= 1, "Duplicate owner-request metadata."); + const comment = matches[0]; + if (!comment || comment.author?.type !== "User" || comment.author.login !== OWNER.login || + comment.minimized || comment.lastEditedAt !== null || thread.target.state !== "OPEN" || thread.target.locked) { + return { eligible: false, reason: "The owner request is unavailable, edited, withdrawn, closed, or locked; no receipt was posted." }; + } + requireValue(Date.parse(comment.createdAt) <= created, "The source run predates this owner command."); + const prefix = /^\/typechat (draft|reply)/.exec(comment.body); + if (!prefix) { + return { eligible: false, reason: "The source comment is not a discussion draft/reply request." }; + } + const valid = comment.body.length <= 2000 && /^\/typechat (draft|reply)\s*$/.test(comment.body); + const request = { + target, commentId: comment.id, commandBody: comment.body, commandCreatedAt: comment.createdAt, + command: valid ? parseCommand(comment.body) : null, + }; + await verifyOwnerCommand(github, request); + const data = { + version: 1, ...locator, runId: run.id, attempt: run.run_attempt, started, + action: prefix[1], outcome: "failed", result: "", + }; + let artifact = null; + let existing = null; + if (!valid) { + data.outcome = "invalid"; + } else if (request.command.action === "reply" && (existing = existingReply(thread, request))) { + data.outcome = "replied"; + const result = new RegExp(`^${target.url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}#(?:issuecomment|discussioncomment)-([A-Za-z0-9_-]{1,128})$`).exec(existing.url); + requireValue(result, "The existing reply has an invalid target URL."); + data.result = result[1]; + } else if (["cancelled", "timed_out"].includes(run.conclusion)) { + data.outcome = "cancelled"; + } else if (request.command.action === "reply") { + data.outcome = "unconfirmed"; + } else if (run.conclusion === "success") { + const produced = await readControls(github, run.head_sha); + if (!equal(produced.fingerprints, controls.fingerprints)) { + data.outcome = "outdated"; + } else { + const name = `${DRAFT_ARTIFACT_PREFIX}${run.run_attempt}`; + const response = (await github.rest.actions.listWorkflowRunArtifacts({ + ...API_REPO, run_id: run.id, name, per_page: 2, page: 1, + })).data; + requireValue(response && Array.isArray(response.artifacts) && + Number.isSafeInteger(response.total_count) && response.total_count >= 0 && + response.total_count <= 1 && response.artifacts.length === response.total_count, + "The sealed-output listing is incomplete or ambiguous."); + artifact = response.artifacts[0] ?? null; + data.outcome = "unavailable"; + if (artifact) { + integer(artifact.id, "Missing sealed artifact ID."); + requireValue(artifact.name === name && artifact.workflow_run?.id === run.id && + artifact.workflow_run.repository_id === REPOSITORY.id && + artifact.workflow_run.head_repository_id === REPOSITORY.id && + artifact.workflow_run.head_sha === run.head_sha && + Number.isSafeInteger(artifact.size_in_bytes) && artifact.size_in_bytes > 0 && + artifact.size_in_bytes <= MAX_BUNDLE_BYTES * 2, + "The receipt artifact does not belong to the successful source run."); + timestamp(artifact.created_at, "Missing sealed artifact creation time."); + timestamp(artifact.expires_at, "Missing sealed artifact expiry."); + requireValue(typeof artifact.expired === "boolean" && + Date.parse(artifact.created_at) >= created && Date.parse(artifact.created_at) <= now, + "The sealed artifact has invalid availability or timing metadata."); + if (artifact.expired !== false || now >= Math.min(Date.parse(artifact.expires_at), Date.parse(artifact.created_at) + MAX_AGE_MS)) { + artifact = null; + } + } + } + } + return { eligible: true, request, thread, data, run, artifact, controls, existing, validUntil: started + MAX_AGE_MS }; +} + +async function statusPlan(github, context, env, bundle, clock) { + const status = await identifyStatus(github, context, env, clock); + if (!status.eligible) { + return { shouldWrite: false, reason: status.reason }; + } + if (status.artifact) { + validateSealedDraft(bundle, status); + requireValue(equal(bundle.request, originalRequest(status.request)), "The sealed output belongs to another owner command."); + status.data.outcome = snapshotHash(status.thread) !== bundle.snapshotHash || + await changedReference(github, bundle.draft.pullRequests) !== null ? "outdated" : + bundle.acceptance ? "ready" : "input"; + } + const key = statusKey(status.data); + const prefix = `